jQuery $.getScript - old functions & variables in

2019-08-18 04:16发布

问题:

i execute a javascript with jQuery $.getScript. In the executed script i haven't access to the functions and variables of my source file.

Is there a solution?

回答1:

The script executed by $.getScript() does have access to the global context. You can use any global variable (or function for that matter) from within your external script.



回答2:

Nick Craver, I just spend 3 (!) hours obsessing over why my thing wouldn't work, and you gave me the insight I needed to make it work.

XOXOXOXOXOXOXOXO

interesting to note:

you can declare a variable as a jquery var like this:

$variableName = something;

That way jquery also has access to it from anywhere in the scope.

$(function(){ 
    $alertString = 'Hello World'; 

    $.getScript('test.js', function(){ 
        // do nothing 
    });    
} 

test.js: 

alert( $alertString ); 


回答3:

I found the answer here helpful for my grasp of the topic, but I still couldn't make it work in my own context until I happened upon this article on TechMonks:

When I copy/pasted their final example into the head of my main .js file it all just worked. For me at least, the $.getScript() function was broken, and this is the fix:

jQuery.extend({
 getScript: function (url, callback) {
     var head = document.getElementsByTagName("head")[0] || document.documentElement;
     var script = document.createElement("script");
     script.src = url;

     // Handle Script loading
     {
         var done = false;

         // Attach handlers for all browsers
         script.onload = script.onreadystatechange = function () {
             if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
                 done = true;
                 //success();
                 //complete();
                 if (callback) callback();

                 // Handle memory leak in IE
                 script.onload = script.onreadystatechange = null;
                 if (head && script.parentNode) {
                     head.removeChild(script);
                 }
             }
         };
     }

     head.insertBefore(script, head.firstChild);
     return undefined;
 }
});