Created
February 17, 2011 02:16
-
-
Save rixth/830812 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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