Last active
January 8, 2019 14:01
-
-
Save willbroderick/9e5aed08164158fa93b4cb1dcc7da704 to your computer and use it in GitHub Desktop.
Load a script from a URL, with before/after callbacks & queueing
This file contains 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
// 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