Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Asynchronous JS script loader. Not clever or modern - just works.
//js async loader
var $$ = $$ || {};
$$.asyncScriptLoader = function (url) {
//get currently loaded scripts
var allScripts = document.getElementsByTagName('script'),
alreadyLoaded = false;
function onLoad(){}; //url is parameter
function onError(){}; //url is parameter
function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
};
var patt = new RegExp(escapeRegExp(url)+'$');
//is script to be loaded already there? (looks at end of script urls only)
for(var i = 0, len = allScripts.length;i < len; i++) {
if(patt.test(allScripts[i].src)) {
alreadyLoaded = true;
break;
};
};
//if already loaded skip load, just do any callback
if(!alreadyLoaded) {
// Create a new script and setup the basics.
var script = document.createElement("script");
script.async = true;
script.src = url;
script.onerror = function(){
onError(url);
script.onload = script.onreadystatechange = script.onerror = undefined;
};
script.onload = function() {
onLoad(url);
// Clear it out to avoid getting called more than once or any memory leaks.
script.onload = script.onreadystatechange = script.onerror = undefined;
};
script.onreadystatechange = function() {
if ( "loaded" === script.readyState || "complete" === script.readyState ) {
script.onload();
};
};
// Attach the script tag to the page (before the first script) so the magic can happen.
allScripts[0].parentNode.insertBefore(script, allScripts[0]);
} else {
//already loaded, do the success callback
//needs this fn to return so any success handler can be attached so
//delay the call by min timeout value.
setTimeout(function(){
onLoad();
},0);
};
//export chain
return {
success: function(fn){
onLoad = (typeof fn === 'function') ? fn : onLoad;
return this;
},
error: function(fn){
onError = (typeof fn === 'function') ? fn : onError;
return this;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.