BenR
BenR

Reputation: 2936

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.
    });
});

Upvotes: 3

Views: 4788

Answers (4)

Paul Bruno
Paul Bruno

Reputation: 1906

There's a few different ways to do this... via libraries or "by hand," so to speak, using only the browser APIs and straight JavaScript. For an answer on how to do this in JS only, look here for Stoyan's post to give you guidance. Basically, the gist of it is setting an event handler to both the script's unload and onreadystatechange properties and then check to see if the readyState is "loaded" or "complete" (if it exists at all). It would look something like this:

var done = false;
newScript.onload = newScript.onreadystatechange = function () {
    if (!done && (!newScript.readyState || newScript.readyState === "loaded" || newScript.readyState === "complete)) {
        done = true;
        // run your actual code here
    }
};

Upvotes: 0

chaos
chaos

Reputation: 124365

Using jQuery (as you've tagged), it's extremely easy:

$.getScript('/script.js', function() {
    foo.bar();
});

Upvotes: 1

Brendan Delumpa
Brendan Delumpa

Reputation: 1145

If you want more robust module loading functionality, then require.js works great in this capacity. Check out: http://requirejs.org/docs/why.html for an overview. I use require.js specifically for lazy-loading script modules.

Upvotes: 1

fanfavorite
fanfavorite

Reputation: 5199

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

Upvotes: 3

Related Questions