Skip to content

Instantly share code, notes, and snippets.

@umayr
Created April 15, 2021 17:44
Show Gist options
  • Save umayr/1ea946ee1a5702ce35c297cf774e29c3 to your computer and use it in GitHub Desktop.
Save umayr/1ea946ee1a5702ce35c297cf774e29c3 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
// 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