-
-
Save fanyer/e95e3f26bbdfdb5b13704cf71c5e9d6d to your computer and use it in GitHub Desktop.
Async load a script in the page and run it. Uses promises
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
// this function will work cross-browser for loading scripts asynchronously | |
function loadScript(src) { | |
return new Promise(function(resolve, reject) { | |
const s = document.createElement('script'); | |
let r = false; | |
s.type = 'text/javascript'; | |
s.src = src; | |
s.async = true; | |
s.onerror = function(err) { | |
reject(err, s); | |
}; | |
s.onload = s.onreadystatechange = function() { | |
// console.log(this.readyState); // uncomment this line to see which ready states are called. | |
if (!r && (!this.readyState || this.readyState == 'complete')) { | |
r = true; | |
resolve(); | |
} | |
}; | |
const t = document.getElementsByTagName('script')[0]; | |
t.parentElement.insertBefore(s, t); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment