Skip to content

Instantly share code, notes, and snippets.

@nmcgann
Created February 10, 2017 16:43
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 nmcgann/dec4bf8f203d74d1139d66bd9f9922d7 to your computer and use it in GitHub Desktop.
Save nmcgann/dec4bf8f203d74d1139d66bd9f9922d7 to your computer and use it in GitHub Desktop.
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