-
-
Save marcus-at-localhost/5f11631af6b0807d8b762673e68f3786 to your computer and use it in GitHub Desktop.
How to inject the script in the body of the document and wait till it has been loaded completely
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
// injects the script in the body of the document. | |
// returns a promise that gets resolves once the script has been loaded in the document | |
export const injectScript = (url, document = window.document) => { | |
const script = document.createElement('script'); | |
script.src = url; | |
script.type = 'text/javascript'; | |
script.async = true; | |
const body = document.getElementsByTagName('body')?.[0] ?? null; | |
if (body === null) { | |
throw ERR_UNKNOWN; | |
} | |
return new Promise((resolve, reject) => { | |
script.addEventListener('load', () => { | |
resolve(script); | |
}); | |
script.addEventListener('error', () => { | |
reject(new Error('unable to load translation script')); | |
}); | |
body.appendChild(script); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment