Skip to content

Instantly share code, notes, and snippets.

@cjkoepke
Created January 11, 2018 17:52
Show Gist options
  • Save cjkoepke/ef42e388dc4a3f80ec0dc1bc826da187 to your computer and use it in GitHub Desktop.
Save cjkoepke/ef42e388dc4a3f80ec0dc1bc826da187 to your computer and use it in GitHub Desktop.
Load script/style dependencies asynchronously using Promises.
// 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