Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing cache expiration from a JavaScript file

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.

like image 400
Bilal and Olga Avatar asked Feb 23 '10 17:02

Bilal and Olga


People also ask

How do I set my cache to expire?

To set output-cache expirations for a page programmatically In the page's code, set the expiration policy for the page on the Cache property of the Response object. If you set expirations for a page programmatically, you must set the Cache-Control header for the cached page as well.

How do I force a JavaScript refresh?

The easiest solution is the hard reload your browser. Users can hard reload their browser by pressing ctrl + F5 or ctrl + shift + R after opening the application window.


2 Answers

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.

like image 58
Matt Avatar answered Oct 15 '22 00:10

Matt


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

like image 20
meltix Avatar answered Oct 15 '22 01:10

meltix