Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force JavaScript to wait until after a dynamically added script file has completed loading?

I'm trying to write a function which will append a javascript file to the DOM, but I am looking to have the rest of the code wait until the newly added JS file is completely loaded. Here is an example of what I am trying to accomplish, although this code doesn't work properly:

$(document).ready(function () {
    var newScript = document.createElement("script");
    newScript.setAttribute("type", "text/javascript");
    newScript.src = "http://www.domain.com/script.js";
    document.getElementsByTagName("body")[0].appendChild(newScript);
    $(newScript).ready(function () { // This is the idea of what I'm trying to do, but this doesn't seem to actually wait until the new file is completely loaded.
        foo.bar(); // foo is a new global variable which is declared in the newScript. This causes an error "foo is not defined".
        // Here is where more code I wish to execute should continue.
    });
});
like image 795
BenR Avatar asked May 10 '26 23:05

BenR


1 Answers

As Musa mentioned in the comments above. Use jQuery's getScript and use the success callback function to trigger your other functions.

like image 71
fanfavorite Avatar answered May 13 '26 12:05

fanfavorite