Created
January 11, 2018 17:52
-
-
Save cjkoepke/ef42e388dc4a3f80ec0dc1bc826da187 to your computer and use it in GitHub Desktop.
Load script/style dependencies asynchronously using Promises.
This file contains hidden or 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
// Use the function like so: | |
_loadDependecies([ | |
{tag: 'script', url: 'example.com/asset.js'}, | |
{tag: 'script', url: 'example.com/asset2.js'}, | |
{tag: 'link', url: 'example.com/asset.css'} | |
]).then(() => { | |
// Do something. | |
}); | |
// Function to return a promise catch-all. | |
function _loadDependecies( assets = [] ) { | |
const promises = assets | |
.filter(asset => 'script' === asset.tag || 'link' === asset.tag) | |
.map(asset => new Promise((resolve, reject) => { | |
const tag = document.createElement(asset.tag); | |
// Set source attributes. | |
if ( 'script' === asset.tag ) { | |
tag.src = asset.url; | |
tag.type = 'text/javascript'; | |
} else { | |
tag.href = asset.url; | |
tag.rel = 'stylesheet'; | |
} | |
// Resolve on load. | |
tag.addEventListener('load', (e) => { | |
resolve() | |
}); | |
// If bad URL, reject Promise. | |
tag.addEventListener('error', () => { | |
reject( `Bad dependency URL: ${asset.url}`); | |
}); | |
// Append to head. | |
document.querySelector('script').insertAdjacentElement('beforebegin', tag); | |
})); | |
// Return a Promise catch-all. | |
return Promise.all(promises); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment