6

I need to load a variable number of javascript source files before running javascript code that depends on them. Sometimes 1 script needs to be loaded, other times 2. The getScript() method allows one script to be loaded - how could I use it to load x number of scripts before running its inner code?

$.getScript("test.js", function(){
    // code to run after script is loaded
});

What I need:

$.getScript(new Array("1.js","2.js"), function(){
    // code to run after all scripts are loaded
});

Thanks

1
  • I'm very interested in the answers here. Looks like a there's a few good choices: jQuery's own .getScript() method or any of the libraries mentioned (LABjs, HEADjs etc.) -- Thanks folks!! Commented Jun 9, 2011 at 15:49

6 Answers 6

18

If you are using jquery 1.5 you can use the new deferred syntax.

$.when(
    $.getScript("1.js"), 
    $.getScript("2.js"), 
    $.getScript("3.js")
).then(function(){
    alert("all loaded");
});

Just pass in the scripts you wish to load.

Sign up to request clarification or add additional context in comments.

2 Comments

@Tom are you using jquery 1.5?
I had the syntax wrong, you don't pass in an array, you simply list the deferreds.
3

I suggest you look into LABjs

That is exactly what its purpose is.

1 Comment

I tried RequireJS (with jQuery 1.5) and I tried the deferred syntax with jQuery 1.5 - LAB was the first thing to work for me. Thanks a lot.
2

I've use RequireJS quite extensively and it's very good. However, this might work for you:

$.getScript("1.js", function(){
    $.getScript("2.js", function () {
        // code to run after all scripts are loaded
    });
});

That's a pretty nasty and little block of code there, IMO, but if it is actually only two scripts like that, it's probably worth it. The logic of the above could also be extracted to a generic function, but once you go too far down that path, it's probably smarter to use RequireJS, or LABjs as JAAulde suggested.

2 Comments

I tried this with 1.5 and it didn't work. I see an unknown $ function in the console. LAB worked with 1.5
Of course I loaded jQuery. The console error appears before even executing the require() method - maybe a 1.5 incompatibility?
1

One way is to list all your scripts in an array, track how many scripts have loaded vs. the amount you want to load. Something like this:

var toLoad = ["1.js", "2.js", "3.js"], loaded = 0;

var onLoaded = function() {
    loaded++;
    if (loaded == toLoad.length) {
        console.log('All scripts loaded!');
    } else {
        console.log('Not all scripts are loaded, waiting...');
    }
}

for (var i = 0, len = toLoad.length; i < len; i++) {
    $.getScript(toLoad[i], onLoaded);
}    

Comments

0

Wrote this earlier tonight, but I promise I'm not a plant. ;-) In addition to LabJS and RequireJS, there's also Head.js which is dead simple to use and does exactly what you want.

1 Comment

Easy enough to Google "Head.js" I would think. The link restrictions on new users make me 'reserve' my links, and alas I forgot.
0

Loading multiple scripts by $.getScript() one after the other and do stuff after all the scripts are loaded

Working Fiddle. Check the Console window for the output

We can create a function to which we pass array of js file paths, this function will do a $.getScript() for the first js file and on success method it will call the same function by passing the second js file index, and this on success will call the same function by passing 3rd file index and so on until it loads the last file. So its basically a recursion function which will give a callback when all the files in the array has been loaded.The end code would be as simple as

LoadAllScripts("yourArray",function(){
  alert("all scripts loaded!!");
 });

So the complete code would go like this.

 var LoadAllScripts = function (scriptArray, callback) {   
   SyncLoadScript({ scriptArray: scriptArray, index: 0}, function () {
        callback();
    });
};

And SyncLoadScript (core of the logic) looks like

 var SyncLoadScript = function (scriptConfig, callback) {
    var $this = this;
    var script = scriptConfig.scriptArray[scriptConfig.index];
    if (scriptConfig.scriptArray.length > scriptConfig.index) {
        if (script.trim().length > 0) {
            $.getScript(script, function () {
                console.log(script);
                SyncLoadScript({ scriptArray: scriptConfig.scriptArray, index: ++scriptConfig.index, element: scriptConfig.element }, callback);
            }).fail(function (jqXHR, textStatus, errorThrown) {
                console.log(script + " failed while loading");
                debugger;
                console.log("Error: "+errorThrown);
                SyncLoadScript({ scriptArray: scriptConfig.scriptArray, index: ++scriptConfig.index, element: scriptConfig.element }, callback);
            });         
        }
        else {
            console.log("invalid script src!!");           
        }
    }
    else {
        callback();
    }
}

Then you can make a simple call to LoadAllScripts by passing array of js file path. like below.

LoadAllScripts(["1.js","2.js","3.js","4.js"], function () {
    console.log("All the scripts have been loaded.");
    //do your stuff after all the scripts are loaded.
});

Note: I have given empty callbacks for you guys to make tweaks and pass around any data of choice. probably to hold all the failed scripts that you can passback to the main function and try to reload them again.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.