0

can I somehow enforce a browser-reload? I'm already using this:

header("Expires: Mon, 2 Jan 2012 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");

But if I change for example JavaScript-Code in my website, the visitors of my website have to manually reload the page for an updated javascript. Do I have to send headers in the .js files also? How to do this?

Inna
  • 367
  • 3
  • 12
  • 1
    How often do your JS files change?!? – kittycat Nov 16 '12 at 07:54
  • Your question is not clear. On what event you want to reload browser? Means what happens when browser should be reloaded? What is meant by `But if I change for example JavaScript-Code in my website`?. What is meant by this change? – Awais Qarni Nov 16 '12 at 07:54
  • [window.location.reload()](http://www.w3schools.com/jsref/met_loc_reload.asp) – Tyranron Nov 16 '12 at 07:54
  • 3
    see this question What is an elegant way to force browsers to reload cached CSS/JS files? http://stackoverflow.com/questions/118884/what-is-an-elegant-way-to-force-browsers-to-reload-cached-css-js-files – Amitd Nov 16 '12 at 07:57
  • with "change" I mean coding a new version of the javascript, which could happen weekly, or fix a bug - it is important that the new version of the file is used and not the one in the browsers cache. – Inna Nov 16 '12 at 08:13
  • 1
    `window.location.reload(true);` will reload the page from the server but I don't think that it's what you really want to do. As said lower, you can use timestamp or version of the file in a query string, or even in the file-name (using url rewriting or not). – Bali Balo Nov 16 '12 at 08:16
  • OK, the better way is not using GET-Parameter but changing the filename itself. I could add versioning info in the filename. I think that is better than a timestamp, the file has only to be reloaded when it really changes. Instead of myOwnJavaFile.js I will use myOwnJavaFile-V2-0-3.js and each modification changes the version. Because I use SVN I can't change the filename locally each time. So I will also use mod_rewrite for a mapping of the versioned filename to the simple filename. This should be a practical solution. Thanks everyone – Inna Nov 16 '12 at 09:03

1 Answers1

1

Browsers should probably be better about this, but change this:

<script src="file.js">

to this:

<script src="file.js?last-modified-time-goes-here">

This will load the latest JS file each time and you don't have to change the filename!

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • 2
    Some caching proxy doesn't like the query string way, if you have access to the webserver, try embedding the timestamp into the filename and have rewirte rules to map to the real files. – complex857 Nov 16 '12 at 07:59