Last active
November 28, 2017 10:01
-
-
Save fedecarg/99d288be2d8a696967f1d3d2480ad26d to your computer and use it in GitHub Desktop.
Load scripts asynchronously
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
| const loadScript = (uri) => { | |
| return new Promise((resolve, reject) => { | |
| const el = document.createElement('script'); | |
| el.type = 'text/javascript'; | |
| el.src = uri; | |
| if (id) { | |
| const docEl = document.getElementById(id); | |
| if (docEl) { | |
| docEl.parentNode.removeChild(docEl); | |
| } | |
| el.id = id; | |
| } | |
| el.onload = () => { | |
| el.onload = el.onerror = null; | |
| if (resolve) { | |
| resolve(); | |
| } | |
| }; | |
| el.onerror = () => { | |
| el.onload = el.onerror = null; | |
| if (reject) { | |
| reject(); | |
| } | |
| }; | |
| document.head.appendChild(el); | |
| }; | |
| }; | |
| loadScript('http://path/to/script.js').then( | |
| (data) => { | |
| console.log('success'); | |
| console.log(data); | |
| }, | |
| (error) => { | |
| console.log(error); | |
| } | |
| ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment