Can We Prevent CSS Caching?
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
There is a little trick that I believe comes from the land of javascript programmers. To prevent the caching of their scripts, they add a timestamp to the end of the src link. 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" />
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.
So 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?
http://css-tricks.com
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.



Leave a Reply