Bilal and Olga
Bilal and Olga

Reputation: 3251

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.

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

Upvotes: 10

Views: 15675

Answers (4)

Matt
Matt

Reputation: 75317

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.

Upvotes: 19

nombrote
nombrote

Reputation: 41

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.

Upvotes: 0

meltix
meltix

Reputation: 311

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

Upvotes: 8

Pointy
Pointy

Reputation: 413709

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.

Upvotes: 1

Related Questions