Created
October 6, 2022 15:02
-
-
Save PaulRosset/4f51b1206ff368f3f0cb59a7ad3e28a3 to your computer and use it in GitHub Desktop.
Load a script in the page programatically in javascript.
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(src, { scriptId = '', insertBeforeAllTags = false } = {}) { | |
return new Promise((resolve, reject) => { | |
let script = document.createElement('script'); | |
script.id = scriptId; | |
script.onload = resolve; | |
script.onerror = event => { | |
reject(new ExternalScriptError(event.target.src)); | |
}; | |
script.src = src; | |
if (insertBeforeAllTags) { | |
let firstScriptTagInDocument = document.getElementsByTagName('script')[0]; | |
firstScriptTagInDocument.parentNode.insertBefore(script, firstScriptTagInDocument); | |
} else { | |
document.body.appendChild(script); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment