Created
November 17, 2016 18:37
-
-
Save james2doyle/28a59f8692cec6f334773007b31a1523 to your computer and use it in GitHub Desktop.
Async load a script in the page and run it. Uses promises
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
// 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