Guest User

Untitled

a guest
Jan 21st, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. // Use the function like so:
  2. _loadDependecies([
  3. {tag: 'script', url: 'example.com/asset.js'},
  4. {tag: 'script', url: 'example.com/asset2.js'},
  5. {tag: 'link', url: 'example.com/asset.css'}
  6. ]).then(() => {
  7. // Do something.
  8. });
  9.  
  10. // Function to return a promise catch-all.
  11. function _loadDependecies( assets = [] ) {
  12. const promises = assets
  13. .filter(asset => 'script' === asset.tag || 'link' === asset.tag)
  14. .map(asset => new Promise((resolve, reject) => {
  15. const tag = document.createElement(asset.tag);
  16.  
  17. // Set source attributes.
  18. if ( 'script' === asset.tag ) {
  19. tag.src = asset.url;
  20. tag.type = 'text/javascript';
  21. } else {
  22. tag.href = asset.url;
  23. tag.rel = 'stylesheet';
  24. }
  25.  
  26. // Resolve on load.
  27. tag.addEventListener('load', (e) => {
  28. resolve()
  29. });
  30.  
  31. // If bad URL, reject Promise.
  32. tag.addEventListener('error', () => {
  33. reject( `Bad dependency URL: ${asset.url}`);
  34. });
  35.  
  36. // Append to head.
  37. document.querySelector('script').insertAdjacentElement('beforebegin', tag);
  38. }));
  39.  
  40. // Return a Promise catch-all.
  41. return Promise.all(promises);
  42. }
Add Comment
Please, Sign In to add comment