Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Created November 17, 2016 18:37
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save james2doyle/28a59f8692cec6f334773007b31a1523 to your computer and use it in GitHub Desktop.
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 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