Last active
March 10, 2023 01:02
-
-
Save tohagan/53d2cd66ef2d758e0e6345ec941c821b to your computer and use it in GitHub Desktop.
Dynamically load a script with callback (JS) or Promise (TS)
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
function loadScript(id, src, async = true, onload = undefined, onerror = undefined) { | |
var elScript = Object.assign(document.createElement('script'), { | |
id, src, async, type: 'text/javascript' | |
}) | |
if (onload) elScript.addEventListener("load", onload); | |
if (onerror) elScript.addEventListener("error", onerror); | |
document.head.appendChild(elScript) | |
} | |
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
export async function loadScript(id: string, src: string, async = true): Promise<void> { | |
return new Promise((accept, reject) => { | |
const elScript = Object.assign(document.createElement('script'), { | |
id, src, async, type: 'text/javascript' | |
}) | |
elScript.addEventListener("load", () => accept()); | |
elScript.addEventListener("error", () => reject('Failed to load ' + src)); | |
document.head.appendChild(elScript) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment