Created
August 29, 2018 08:29
-
-
Save Fintan/b5b0f7914bd3c32b4d9633c11eafada1 to your computer and use it in GitHub Desktop.
load CDN libraries with fallback options
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
| /** | |
| * Asynchronously loads a script | |
| * A src with fallback/s, can be defined as an array of paths. | |
| * | |
| * @param src {String|Array<String>} the script to load | |
| * @param containerEl {HTMLElement} element to append script tag | |
| * @return {Promise} | |
| */ | |
| const loadScript = ({ src, containerEl }) => { | |
| let srcs; | |
| if(Array.isArray(src)) { | |
| [srcs, src] = [src, src.shift()]; | |
| } | |
| return new Promise((accept, reject) => { | |
| const script = document.createElement('script'); | |
| script.addEventListener('load', () => accept(src)); | |
| script.addEventListener('error', e => { | |
| if(srcs.length) { | |
| accept(this.loadScript({ src: srcs, containerEl })); | |
| }else { | |
| reject(e); | |
| } | |
| }); | |
| script.src = src; | |
| script.async = true; | |
| containerEl.appendChild(script); | |
| }); | |
| }; | |
| const src = ['does-not-exist.js','https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.core.js']; | |
| this.loadScript({ src , containerEl }) | |
| .then(() => console.log('success'), (e) => console.log('problem with', this.interaction)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment