Created
May 24, 2018 09:20
-
-
Save gustafnk/16fa51aed3269a608ad823d83e33eed6 to your computer and use it in GitHub Desktop.
A tweak on https://www.html5rocks.com/en/tutorials/speed/script-loading/ with conditional loading for polyfills
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
window.loadScripts = function(scripts){ | |
var src; | |
var script; | |
var pendingScripts = []; | |
var firstScript = document.scripts[0]; | |
// Watch scripts load in IE | |
function stateChange() { | |
// Execute as many scripts in order as we can | |
var pendingScript; | |
while (pendingScripts[0] && pendingScripts[0].readyState == 'loaded') { | |
pendingScript = pendingScripts.shift(); | |
// avoid future loading events from this script (eg, if src changes) | |
pendingScript.onreadystatechange = null; | |
// can't just appendChild, old IE bug if element isn't closed | |
firstScript.parentNode.insertBefore(pendingScript, firstScript); | |
} | |
} | |
// loop through our script urls | |
while (src = scripts.shift()) { | |
if (src.test && src.test()) continue; | |
if ('async' in firstScript) { // modern browsers | |
script = document.createElement('script'); | |
script.async = false; | |
script.src = src.src; | |
document.head.appendChild(script); | |
} | |
else if (firstScript.readyState) { // IE<10 | |
// create a script and add it to our todo pile | |
script = document.createElement('script'); | |
pendingScripts.push(script); | |
// listen for state changes | |
script.onreadystatechange = stateChange; | |
// must set src AFTER adding onreadystatechange listener | |
// else we’ll miss the loaded event for cached scripts | |
script.src = src.src; | |
} | |
else { // fall back to defer | |
document.write('<script src="' + src.src + '" defer></'+'script>'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment