0

I have a few static html pages. All these pages have the following

<script src="my-javascript.js"></script>

I don't want the browser to cache the javascript file, and I want it to get reloaded at page load for each page.

After online search, I found that this trick: adding the following to each page

<script src="my-javascript.js?p=changing_value"></script>

If this is going to work, how can I generate the "changing_value" in a static html page (not PHP, JSP, etc.).

Or some other solutions to force reload the javascript file at each page load for all pages?

Thanks!

UPDATE

I dont have access to server configuration.

2 Answers 2

1

After online search, I found that this trick: adding the following to each page

A much better solution is to use caching headers to tell the browser not to cache the file. Configure your server to serve that file with:

Cache-Control: no-cache
Expires: -1

Those are the basic ones, anyway.

If this is going to work, how can I generate the "changing_value" in a static html page (not PHP, JSP, etc.).

If you want to go the query string route, though, just for completeness:

You can get a random value from Math.random(), or as Hemadeus points out, use a timestamp value.

If you need the script load to be blocking (like script tags normally are), this is one of the few remaining use cases for document.write:

<script>
document.write('<script src="my-javascript.js?' + Math.random() + '"><\/script>');
</script>

(Or replace Math.random() with Date.now() to use a timestamp)

If you don't need it to be blocking, then creating the element with createElement is probably cleaner:

<script>
(function() {
    var s = document.createElement('script');
    s.src =  "my-javascript.js?" + Math.random();
    document.querySelector("head").appendChild(s);
})();
</script>

Old browsers won't have Date.now. You can get the same value from new Date().getTime().

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

3 Comments

Unfortunately, configuring the server is beyond my access. I have to do it differently. Thanks for your input!
@curious1: I added an example of using the query string trick as well.
T.J. Crowder, thanks so much for your solution, which is not only working, but also teaching me a few other things. Thanks so much!
1

You could generate the changing_value using a Javascript timestamp. so you will always have a new version of the js file.

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.