Last active
August 4, 2021 15:19
-
-
Save simonsmith/8c30037f2cf625b00b9fa415302e7fd8 to your computer and use it in GitHub Desktop.
Simple script loader
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
const scripts = new Map<string, Promise<unknown>>(); | |
export function loadScript( | |
src: string, | |
additionalScriptAttrs: Record<string, string> = {} | |
): Promise<unknown> { | |
if (scripts.has(src)) { | |
// TypeScript cannot narrow down type with `has` | |
// https://github.com/microsoft/TypeScript/issues/13086 | |
return scripts.get(src) as Promise<unknown>; | |
} | |
const script = document.createElement('script'); | |
script.async = true; | |
Object.entries(additionalScriptAttrs).forEach(([attr, value]) => { | |
script.setAttribute(attr, value); | |
}); | |
const promise = new Promise((resolve, reject) => { | |
script.addEventListener('load', resolve); | |
script.addEventListener('error', () => | |
reject(new Error(`Failed to load script: ${src}`)) | |
); | |
script.src = src; | |
document.head.appendChild(script); | |
}); | |
scripts.set(src, promise); | |
return promise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment