Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading