2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.