Peter Peter - 1 year ago 111
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";


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')

Answer Source

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;
    } else {
        // handle other browsers
        script.onload = function(){

    script.src = url;


loadScript("", function(){
    // jquery is loaded