How to Force the Browser to Reload Cached CSS and JavaScript Files

Force browser to refresh CSS, JavaScript, etc

General solution

Pressing Ctrl + F5 (or Ctrl + Shift + R) to force a cache reload. I believe Macs use Cmd + Shift + R.

PHP

In PHP, you can disable the cache by setting the expiration date to a time in the past with headers:

header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

Chrome

Chrome's cache can be disabled by opening the developer tools with F12, clicking on the gear icon in the lower right corner and selecting Disable cache in the settings dialog, like this:

Sample Image

Image taken from this answer.

Firefox

Type about:config into the URL bar then find the entry titled network.http.use-cache. Set this to false.

Forcing the browser to reload css/js only if they have changed

It may not be the best way, but this is what I am doing now:

  1. All of my js/css have a [source control = svn] revision number
  2. References in my jsp are like /foo/path1/path2/xyz000000/foo.
  3. Build Step 1 - Generate a map of css|js files and their revision numbers
  4. Build Step 2 - Replace xyz000000 references in jsps with a hash of svn revisions
  5. A rule in url rewriter to direct all /foo/path1/path2/xyz<767678>/foo. to /foo/path1/path2/foo.[js|css]
  6. Infinitely cache the css|js files
  7. Whenever there is a commit, the revision number changes and so do the references in .jsp

How can I force clients to refresh JavaScript files?

As far as I know a common solution is to add a ?<version> to the script's src link.

For instance:

<script type="text/javascript" src="myfile.js?1500"></script>

I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags?

You might have a version control system do that for you? Most version control systems have a way to automatically inject the revision number on check-in for instance.

It would look something like this:

<script type="text/javascript" src="myfile.js?$$REVISION$$"></script>

Of course, there are always better solutions like this one.

CSS doesn't update

It's cool that sites like GitHub offer free hosting, but I'm not always clear how they manage caching of files. One thing you can do is add a query string to the URL, which will force the browser to fetch a fresh copy:

<link rel="stylesheet" href="style-index.css?v=1" />

The ?v=1 above should do the trick.



Related Topics



Leave a reply



Submit