Created
October 14, 2020 14:40
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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