Peter Peter - 3 months ago 36
Javascript Question

Load JS after JQuery is loaded


Possible Duplicate:






I have included jQuery this way:

function loadScript(loc){
var head = document.getElementsByTagName('head')[0];
var file = document.createElement('script');
file.src = loc;
file.type = "text/javascript";
head.appendChild(file)
}

loadScript("js/jquery.js")


Now the next script should be loaded the same way. But if it is loaded after the last line, I can't use jQuery, because it may not be finished with loading.
So how to check, if the loading of jQuery is done?
Can I do something like this?:

while (typeof jQuery == 'undefined')
{
wait...
}

Answer

The generally accepted method for loading a script dynamically is by creating the script element then appending to the DOM (as you do), but also to assign a callback function to detect when the script is loaded.

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

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

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

Usage:

loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js", function(){
    // jquery is loaded
});