Skip to content

Instantly share code, notes, and snippets.

@rixth
Created February 17, 2011 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rixth/830812 to your computer and use it in GitHub Desktop.
Save rixth/830812 to your computer and use it in GitHub Desktop.
var fetch = (function () {
var scriptStatus = {},
callbackStack = [],
STATUS_LOADING = 1,
STATUS_LOADED = 2;
function requestScript(url) {
if (typeof(scriptStatus[url]) === 'undefined') {
var scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.src = url;
scriptStatus[url] = STATUS_LOADING;
scriptTag.onload = function () {
markLoaded(url);
};
document.body.appendChild(scriptTag);
}
}
function markLoaded(url) {
scriptStatus[url] = STATUS_LOADED;
callbackStack.forEach(function (callbackData, i) {
if (callbackData.scripts.every(function (url) {
return scriptStatus[url] && scriptStatus[url] === STATUS_LOADED;
}) {
callbackData.callback();
delete callbackStack[i];
}
});
}
return function(scripts, callback) {
var scriptsToLoad = scripts.filter(function (url) {
return !scriptStatus[url] || scriptStatus[url] !== STATUS_LOADED;
});
if (!scriptsToLoad.length)
return callback();
}
scriptsToLoad.forEach(function (url) {
requestScript(url);
});
callbackStack.push({
callback: callback,
scripts: scripts
});
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment