Skip to content

Instantly share code, notes, and snippets.

@simonsmith
Last active August 4, 2021 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonsmith/8c30037f2cf625b00b9fa415302e7fd8 to your computer and use it in GitHub Desktop.
Save simonsmith/8c30037f2cf625b00b9fa415302e7fd8 to your computer and use it in GitHub Desktop.
Simple script loader
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