JavaScript - DOM - Dynamic Script Loading

javascript-dom

How can we dynamically load a script?

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "file.js";
document.body.appendChild(script);

There are two things to note about this code. First, the download doesn’t actually begin until the script node is added to the document. This is different from dynamically creating an <img> element, for which assigning the src automatically begins the download even before the node is added to the document. The second thing to note is that you can add the script node either to the <head> or <body>; it really doesn’t matter. That’s all it takes to dynamically load a JavaScript file without blocking the page.

How can we be notified when a dynamic script is loaded?

You may also want to be notified when the JavaScript file is fully downloaded and executed, and that’s where things get a bit tricky.

function loadScript(url, callback){
    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.body.appendChild(script);
}

To use this, just pass in the URL to retrieve and a function to call once it’s loaded:

loadScript("http://yui.yahooapis.com/2.7.0/build/yahoo/yahoo-min.js",
    function(){
        YAHOO.namespace("mystuff");

    //more...
});

See http://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License