Hope this is what you mean: http://jsfiddle.net/pimvdb/hdN3Q/1/ .
(function($) { function load(files, index) { var arr = []; // fill arr with getScript requests (fake here) for(var i = 0; i < files[index].length; i++) { arr.push(console.log(files[index][i])); } // call $.when with arr as array of arguments (using apply) $.when.apply(null, arr).then(function() { if(index < files.length - 1) { // if we have to move to the next chunk, // load that next one setTimeout(function() { // timeout is to show they get processed in chunks load(files, index + 1); }, 1000); } }); } $.loader = function(obj) { load(obj.js, 0); } })(jQuery); $.loader({ js: [ ['1.js','3.js','2.js'], ['4.js'], ['5.js'] ] });
.apply essentially does the same thing as calling a function. However, since the number of $.when arguments differs depending on the input, you cannot just call $.when(...) because you do not have a fixed number of arguments. The method of calling a function with a variable number of arguments uses .apply . It works as follows:
someFunction(1, 2, 3);
equally:
someFunction.apply(null, [1, 2, 3]);
( null refers to the execution context, which is out of scope here.) The great thing is that you can build an array of any size. Thus, you can call a function with any number of arguments in this way.
In load , the arr function is populated with getScript functions, and it works the same way:
var arr = [getScript('file1'), getScript('file2')]; $.when.apply(null, arr);
equally:
$.when(getScript('file1'), getScript('file2'));
In load we populate arr with fragment files, for example. in your case, the first snippet is 1.js , 3.js and 2.js This is done using a for loop, but the array you get into can just jump to .apply .
When all files are loaded, .then is called. The function we go through there should load the next fragment, but only if there is the next fragment. If there are 3 pieces, it should go to the next when index is 0 or 1 . When chunk 2 finished, there is no next fragment, so it should not continue next, since there is no next.
So we need this if clause:
if(index < files.length - 1) {
Say files.length 3 . Then this if conditional will pass only when index is 0 or 1 , what we want.