Dynamically loading Javascript after a page load

  • posted by mark
  • on Dec. 12, 2013
I find this requirement is coming up increasingly more often, particularly as various website analysis tools recommend deferring the loading of Javascript elements until after the initial page load and insist on it when testing for mobile devices. So here's a handy little snippet I threw together to do just that. Firstly we need a pure JS function to load a script. This is done by creating a new script element and attaching it at the bottom of the body element. Here's the function:
function loadScript(path, callback) {

    var done = false;
    var scr = document.createElement('script');

    scr.onload = handleLoad;
    scr.onreadystatechange = handleReadyStateChange;
    scr.onerror = handleError;
    scr.src = path;

    function handleLoad() {
        if (!done) {
            done = true;
            callback(path, "ok");
        }
    }

    function handleReadyStateChange() {
        var state;

        if (!done) {
            state = scr.readyState;
            if (state === "complete") {
                handleLoad();
            }
        }
    }
    function handleError() {
        if (!done) {
            done = true;
            callback(path, "error");
        }
    }
    
    document.body.appendChild(scr);		
}
You can use this function to load a script and execute a callback as soon as it's loaded ... like so:
loadScript('http://code.jquery.com/jquery-1.10.1.min.js', function() {
    alert('I loaded JQuery!');
});
And the bit of code below can be used to load multiple Javascript files, one after the other, once the page has finished loading.
var downloadJsAtOnload_j = 0;
var jsToDownload = ["script1.js", "script2.js"];
function downloadJSAtOnload(e) {
    if(downloadJsAtOnload_j < jsToDownload.length) {
        loadScript(jsToDownload[downloadJsAtOnload_j], function() {
            downloadJsAtOnload_j++;
            downloadJSAtOnload(e);
        });
    } else {
	// All scripts downloaded
    }
}

if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
Simply modify the jsToDownload array with your own scripts. Let me know how this code works for you, interested in any feedback!