Skip to content

Instantly share code, notes, and snippets.

@dsheiko
Created March 6, 2020 12:52
Show Gist options
  • 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