How can I prevent caching when loading javascript with document.createElement('script')?

I am using a technique described by Aaron Smith on https://aaronsmith.online/easily-load-an-external-script-using-javascript/ to dynamically load Javascript code. It works fine when I first create a code file but if I change that file, the browser doesn't pick up the new version. I assume that means the code is being cached in the browser.

Here is my code, which is nearly identical to Aaron's example:

const loadScript = (src) => {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.on   load = resolve;
        script.onerror = reject;
        script.src = src;
        document.head.append(script);
    });
};

How can I ensure that users always load the latest version of my code? I prefer not to change the name of the code file every time I update it. I am also not able to ask users to reconfigure their browsers to run my solution.


Solution 1:

Simply assign a random querystring to make the browser think it's different:

const loadScript = (src) => {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.onload = resolve;
        script.onerror = reject;
        script.src = src + `?dummy=${encodeURIComponent(Math.random())}`;
        document.head.append(script);
    });
};

Every time you load the page you're loading a 'different' script.