Can We Prevent CSS Caching?
Published by Chris Coyier
When you are developing a site, there is a heck of a lot of "refreshing" going on. You start to get a pretty good feel for what your browser is going to pick up on a single refresh, and what it won't. For example, I find that if I over-write an image file on the server, it will take me two refreshes for that image to update on the live site. Then maybe I'll pop over into Opera and see how the site is doing over there, only to find on the first render of the page that is a really old version. Uh oh. Refresh. Refresh. Oh... there it is.
That's fine for you, you are used to that kind of thing. But what if you send that same link to your client, and the same thing happens to them. There is a good chance there will be (at the very least) some confusion. On a larger scale, lets say you roll out a fairly major layout change on a high-traffic website. A huge number of people might see a borked layout the next time they visit, because of CSS caching.
Can we solve this? Is there some way to prevent CSS caching?
Timestamping Your CSS
src attribute. So, let's steal the idea.
I did a quick test to see if this kind of tomfoolery would even fly. Here is how I included the stylesheet link:
<link rel="stylesheet" type="text/css" href="style.css?<?php echo date('l jS \of F Y h:i:s A'); ?>" />
Which results in this:
<link rel="stylesheet" type="text/css" href="style.css?Thursday 24th of April 2008 04:45:21 PM" />
Alter that date format as needed. You might wanna skip spaces.
The theory here is that that link will change every second, and the browser will be tricked into thinking this is a new stylesheet and loading it fresh every time. Jason Edmond Beaird had the same idea and even created a little bookmarklet to force it.
I haven't done any hardcore testing of this, but my early tests suggest that it works pretty well. What do you think folks? Am I just drinking the kool-aid here? Are there any serious problems with doing this? Is there a better/smarter/faster way to do it?
I'm updating this in June 2013 here just to point out a few important things.
In production, breaking cache when you push out new CSS is a very good plan. But breaking cache with a date stamp like presented here would mean you gain no benefit at all from browser caching which would be horrendous for performance. You'd be better off doing something like adding a version number to the end of the file name like
style.css?version=3.2 that you update as needed.
Locally in development, breaking cache every page load might be OK, but modern development tools like Chrome's web inspector can turn off caching anyway.