Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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);
- }
Add Comment
Please, Sign In to add comment