Forcing cache expiration from a JavaScript file

2020-02-12 04:43发布

问题:

I have an old version of a JS file cached on users' browsers, with expiration set to 10 years (since then, I have learned how to set expires headers correctly on my web server). I have made updates to the JS file, and I want my users to benefit from them.

  • Is there any way my web server can force users' browsers to clear the cache for this one file, short of serving a differently named JS file?
  • In the future, if expires headers are not set correctly (paranoia), can my JS file automatically expire itself and force a reload after, say, a day has passed since it was cached?

EDIT: Ideally I want to solve this problem without changing HTML markup on the page that hosts the script.

回答1:

In short... no.

You can add something to the end of the source address of the script tag. Browsers will treat this as a different file to the one they have currently cached.

<script src="/js/something.js?version=2"></script>

Not sure about your other options.



回答2:

In HTML5 you can use Application Cache, that way you can control when the cache should expire

You need to add the path to the manifest

<!DOCTYPE HTML><html manifest="demo.appcache">

In your demo.appcache file you can just place each file that you want to cache

CACHE MANIFEST
# 2013-01-01 v1.0.0
/myjsfile.js

When you want the browser to download a new file you can update the manifest

CACHE MANIFEST
# 2013-02-01 v1.0.1
/myjsfile.js

Just be sure to modify the cache manifest with the publish date or the version (or something else) that way when the browser sees that the manifest has change it will download all files in it.

If the manifest is not change, the browser will not update the local file, even if that file was modify on the server.

For further information please take a look at HTML5 Application Cache



回答3:

You could add a dummy parameter to your URLs

<script src='oldscriptname.js?foo=bar'></script>

[e: f; b]

The main problem is that if you set up the expiration with a simple "Expires" header, then the browsers that have the file cached won't even bother to contact you for it. Even if there were a way for the script to whack the browser in the head and clear the cache, your old script doesn't do that, so you have no way to get that functionality out to the clients.



回答4:

You can force to reload an cacheated document with on javascript:

window.location.reload(true);

The true command indicate the browser must to reload the page without cache.