Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way of getting several scripts asynchronously using Jquery with post-document-ready callback

I'm planning on getting several JS files from my server asynchronously while the page loads. I am aware of the Jquery function "getScript", but this only gets 1 script. Is there any way of specifying a callback to be executed when a batch of scripts have been fetched from the server?

I thought about doing something like this:

$.getScript(script1, function() {
$.getScript(script2, function() {
$.getScript(script3, function() {
...
...
});});....});

But this loads the scripts in sequence, and I'd like the requests to be done in parallel.

As a more general question which supersedes this one, what is the best way of loading N resources (CSS, images, scripts, etc) asynchronously specifying a single callback to be executed when all the resources have been loaded?

Update: In addition to this, I need the callback to be executed after the document is ready (signaled by the $(document).ready event). Any way of achieving this?

like image 439
Diego Avatar asked Sep 21 '10 18:09

Diego


1 Answers

You need to call getScript 3 times in a row, passing a callback which increments a counter and calls the real callback if the counter is 3.

You can make a simple wrapper function to do this:

function getScripts(names, callback) {
    var received = 0;
    var realCallback = function() { 
        received++;
        if (received === names.length)
            $(callback);
    };

    for (var i = 0; i < names.length; i++)
        $.getScript(names[i], realCallback);
}

(Edited to call the callback when the document is ready)

You can call it like this:

getScripts([ "script1", "script2", "script3" ], function() { ... });
like image 87
SLaks Avatar answered Oct 28 '22 12:10

SLaks