DEV Community

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

Discussion (0)