Skip to content

Instantly share code, notes, and snippets.

@fanyer
Forked from james2doyle/get-script-promise.js
Created February 2, 2023 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fanyer/e95e3f26bbdfdb5b13704cf71c5e9d6d to your computer and use it in GitHub Desktop.
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 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