Skip to content

Instantly share code, notes, and snippets.

@dsheiko
Created Mar 6, 2020
Embed
What would you like to do?
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