Created
August 1, 2020 13:11
-
-
Save clshortfuse/af6e9aea205b485a4b8e1a8e1d03cc0b to your computer and use it in GitHub Desktop.
Dynamically load script as a Promise
This file contains 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
/** | |
* @param {string} url | |
* @param {boolean} [useCredentials=false] | |
* @param {string} [integrity] | |
* @return {Promise<void>} | |
*/ | |
export function loadScript(url, useCredentials, integrity) { | |
return new Promise((resolve, reject) => { | |
const scripts = document.head.getElementsByTagName('script'); | |
for (let i = 0; i < scripts.length; i += 1) { | |
if (scripts.item(i).src.toLowerCase() === url) { | |
// already mounted | |
resolve(); | |
return; | |
} | |
} | |
const newScript = document.createElement('script'); | |
newScript.async = true; | |
newScript.src = url; | |
newScript.crossOrigin = useCredentials ? 'use-credentials' : 'anonymous'; | |
if (integrity) { | |
newScript.integrity = integrity; | |
} | |
newScript.addEventListener('load', function fn() { | |
resolve(); | |
newScript.removeEventListener('load', fn); | |
}); | |
newScript.addEventListener('error', function fn(event) { | |
reject(new Error(event.message)); | |
newScript.removeEventListener('error', fn); | |
}); | |
document.head.appendChild(newScript); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment