Skip to content

Instantly share code, notes, and snippets.

@codingtony
Last active August 29, 2015 14:05
Show Gist options
  • Save codingtony/3388893a8d02c56ec0c1 to your computer and use it in GitHub Desktop.
Save codingtony/3388893a8d02c56ec0c1 to your computer and use it in GitHub Desktop.
Example Sequential LoadScripts
function loadScripts(scripts, doneCallback) {
var i = 0;
var fn;
var fns = [];
var slist = [];
var load = function (s, h) {
console.log("Loading JS " + s);
$.getScript(s, h);
};
var loadNext = function () {
var spop = slist.pop();
load(spop, fns.pop());
console.log("Loaded JS " + spop);
};
fns.push(doneCallback);
for (i = scripts.length - 1; i >= 0; i = i - 1) {
slist.push(scripts[i]);
fns.push(loadNext);
}
fn = fns.pop();
if (fn) {
fn();
}
}
console.log("start");
loadScripts(['http://codingtony.com/toto.js', 'http://codingtony.com/tata.js'], function () {
console.log("Load with callback completed");
//Without callback :
loadScripts(['http://codingtony.com/toto.js', 'http://codingtony.com/tata.js']);
// see it in action : http://jsfiddle.net/codingtony/psvyamva/
function loadScripts(scripts) {
// TODO validate that scripts is an array
// the master Deferred object controls the outcome of all the script load process.
var master = $.Deferred();
var nbScriptsLoaded = 0;
var nbScriptsTotal = scripts.length;
//each script to load gets a deferred
var dfrs = scripts.map(function () {
return $.Deferred();
});
// create a promise for each deferred
var promises = dfrs.map(function (d) {
return d.promise();
});
var progress = function (s, state) {
return {
'script': s,
'success': nbScriptsLoaded,
'total': nbScriptsTotal,
'state': state
};
};
var load = function () {
var dd;
var s = scripts.shift();
if (!s) {
return;
}
dd = dfrs.shift(dd);
master.notify(progress(s, 'LOADING'));
$.getScript(s).done(
function () {
nbScriptsLoaded = nbScriptsLoaded + 1;
// chain the next load, and resolve
dd.then(load);
master.notify(progress(s, 'LOADED'));
dd.resolve();
}).fail(function () {
master.notify(progress(s, 'FAILED'));
dd.reject();
});
};
// resolve the master when all promises have succeeded, otherwise reject it.
$.when.apply($, promises).done(function () {
master.resolve();
}).fail(function () {
master.reject();
});
load();
return master.promise();
}
$.when(loadScripts(['http://codingtony.com/toto.js', '/BAD.js', 'http://codingtony.com/tata.js'])).done(function () {
console.log("Load with deferred completed");
}).fail(function () {
console.log("Load deferred FAILED");
}).progress(function (i) {
console.log(i);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment