JavaScript
Article

$.getScript mutiple scripts

By Sam Deering

This is very useful for loading mutiple scripts with a callback function containing code that you want to run only when all of the scripts have been loaded. To load mutiple scripts you need to enhance the AJAX $.getScript() function to handle mutiple scripts then simply add them to an array for the first parameter and the callback function as the second parameter.

Single jQuery Get Script

$.getScript('script1.js', function(data, textStatus) {
    //do something after script has loaded
});

Multiple jQuery Get Scripts

/* enhance $.getSctipt to handle mutiple scripts */
var getScript = jQuery.getScript;
jQuery.getScript = function( resources, callback ) {

    var // reference declaration & localization
    length = resources.length,
    handler = function() { counter++; },
    deferreds = [],
    counter = 0,
    idx = 0;

    for ( ; idx < length; idx++ ) {
        deferreds.push(
            getScript( resources[ idx ], handler )
        );
    }

    jQuery.when.apply( null, deferreds ).then(function() {
        callback && callback();
    });
};

$.getScript(['script1.js','script2.js','script3.js'], function() {
    //do something after all scripts have loaded
});

//or seperate into an array to include

var scripts = ['script1.js','script2.js','script3.js'];
$.getScript(scripts, function(data, textStatus) {
    //do something after all scripts have loaded
});
[/js]

Any way I discovered: You could just do it this way, say you had to load 3 scripts and the third has a callback. [js] $.get("js/ext/flowplayer-3.2.8.min.js") .pipe($.get("js/eviflowplayer.js")) .pipe($.get("js/evi.flowplayer.js", {}, function() { W.EVI.FLOWPLAYER.init(elem.attr('id')); });

  • timrpeterson

    Thanks for the tips!

  • Jeff

    Thanks this was helpful! Along with a
    $.ajaxSetup({ cache: true });

    you can call it from multiple locations in the page and not worry about duplicates. Thanks.

  • Mike Stoddart

    In my tests the callback is never invoked. Does this code still work with the latest version of jQuery?

Recommended
Sponsors
Get the latest in JavaScript, once a week, for free.