Skip to content

Instantly share code, notes, and snippets.

@Pamblam
Created October 14, 2020 14:40
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 Pamblam/26107fd67ac7a7048bb1eba7d6108343 to your computer and use it in GitHub Desktop.
Save Pamblam/26107fd67ac7a7048bb1eba7d6108343 to your computer and use it in GitHub Desktop.
Given a URL for a JS or CSS file, this function will load the asset and return a Promise which will reject on error or resolve when the asset is loaded.
/**
* Given a URL for a JS or CSS file, this function will
* load the asset and return a Promise which will reject
* on error or resolve when the asset is loaded.
*/
function loadAsset(url){
return new Promise(async (resolve, reject)=>{
var asset;
if(url.trim().substr(-3).toLowerCase() === '.js'){
asset = document.createElement('script');
asset.addEventListener('load', resolve);
asset.addEventListener('error', reject);
document.head.appendChild(asset);
asset.setAttribute('src', url);
}else{
var styles = await fetch(url)
.then(c=>c.text())
.catch(reject);
asset = document.createElement('style');
asset.appendChild(document.createTextNode(styles));
document.head.appendChild(asset);
resolve();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment