Created
May 7, 2018 08:14
-
-
Save viclm/ddba40fbd9236df313cf8ae32ccc1922 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function loadScripts(assets, nostore) { | |
if (!('async' in document.createElement('script'))) { | |
assets.forEach(function (asset) { | |
document.write('<script src="' + asset.url + '"><\/script>'); | |
}); | |
return; | |
} | |
if (!nostore) { | |
var valid = assets.every(function (asset) { | |
var cache = localStorage.getItem(asset.key); | |
if (cache) { | |
var index = cache.indexOf('|'); | |
if (cache.substr(0, index) === asset.url) { | |
asset.content = cache.substr(index + 1); | |
return true; | |
} | |
} | |
}); | |
if (valid) { | |
setTimeout(function fn() { | |
if (document.readyState === 'complete') { | |
assets.forEach(function (asset) { | |
var script = document.createElement('script'); | |
script.innerHTML = asset.content; | |
document.head.appendChild(script); | |
}); | |
} | |
else { | |
setTimeout(fn, 50); | |
} | |
}, 50); | |
return; | |
} | |
} | |
assets.forEach(function (asset) { | |
var script = document.createElement('script'); | |
script.onload = function () { | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET', asset.url); | |
xhr.onload = function() { | |
try { | |
localStorage.setItem(asset.key, asset.url + '|' + xhr.responseText); | |
} | |
catch (e) {} | |
}; | |
xhr.send(); | |
}; | |
script.crossorigin = true; | |
script.async = false; | |
script.src = asset.url; | |
document.body.appendChild(script); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment