Skip to content

Instantly share code, notes, and snippets.

@dsheiko
Created March 6, 2020 12:52
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 dsheiko/bd8da5e2460ee11e0521732fe63f8557 to your computer and use it in GitHub Desktop.
Save dsheiko/bd8da5e2460ee11e0521732fe63f8557 to your computer and use it in GitHub Desktop.
Load/execute JavaScript asynchronously
function loadJs(url){
return new Promise( (resolve, reject) => {
if (document.querySelector(`head > script[src="${src}"]`) !== null) return resolve()
const script = document.createElement("script")
script.src = url
script.onload = resolve
script.onerror = reject
document.head.appendChild(script)
});
}
@dsheiko
Copy link
Author

dsheiko commented Mar 6, 2020

Usage:

try { 
 await loadJs("https://.../script.js");
} catch( error ) {
  console.log(error);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment