Monday, August 27, 2012

JQuery : 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
});

No comments: