Skip to content

Instantly share code, notes, and snippets.

@willbroderick
Last active January 8, 2019 14:01
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 willbroderick/9e5aed08164158fa93b4cb1dcc7da704 to your computer and use it in GitHub Desktop.
Save willbroderick/9e5aed08164158fa93b4cb1dcc7da704 to your computer and use it in GitHub Desktop.
Load a script from a URL, with before/after callbacks & queueing
// Load a script from a URL, with callbacks
// If a 'before' callback is specified, script will load synchronously
{
window.scriptsLoaded = {};
window.loadScriptOnce = function(src, callback, beforeRun) {
if(typeof window.scriptsLoaded[src] === 'undefined') {
window.scriptsLoaded[src] = [];
var tag = document.createElement('script');
tag.src = src;
if(beforeRun) {
tag.async = false;
beforeRun();
}
if(typeof callback === 'function') {
window.scriptsLoaded[src].push(callback);
if (tag.readyState) { // IE, incl. IE9
tag.onreadystatechange = (function() {
if (tag.readyState == "loaded" || tag.readyState == "complete") {
tag.onreadystatechange = null;
for(var i = 0; i < window.scriptsLoaded[this].length; i++) {
window.scriptsLoaded[this][i]();
}
window.scriptsLoaded[this] = true;
}
}).bind(src);
} else {
tag.onload = (function() { // Other browsers
for(var i = 0; i < window.scriptsLoaded[this].length; i++) {
window.scriptsLoaded[this][i]();
}
window.scriptsLoaded[this] = true;
}).bind(src);
}
}
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
return true;
} else if(typeof window.scriptsLoaded[src] === 'object' && typeof callback === 'function') {
window.scriptsLoaded[src].push(callback);
} else {
if(typeof callback === 'function') {
callback();
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment