DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,503 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
StuartCreed
StuartCreed

Posted on • Updated on

How to inject JS from a source dynamically

/**
 * Inject a script tag with a src so that you can add JS dynamically
 * @param src
 * @returns { Promise }
 */
export function injectScript(src) {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = src;
        script.addEventListener('load', resolve);
        script.addEventListener('error', e => reject(e.error));
        document.head.appendChild(script);
    });
}
Enter fullscreen mode Exit fullscreen mode

Then e.g:
await injectScript('your src string goes here)
Other code goes here

This allows you to capture errors etc

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.