tags:

views:

293

answers:

3
+4  Q: 

Force CSS Recache

Hi All,

Is there any way to determine or force a CSS file to be re-cached if the user is operating off an old file?

+7  A: 

The single surest way to ensure that everyone reloads your new file is to change its URL. A reasonable way to do this without actually renaming it is to tack on a random string:

<link rel='stylesheet' href='/mystyles.css?random=87365835'>

That's using a sledgehammer to crack a nut, and bypassing all the HTTP mechanisms that exist to do this, but it will absolutely work everywhere, whereas the other techniques all have caveats.

Edit: @jitter: You don't have to change the URL automatically for every request - you could base it on the timestamp of the CSS file, or even just change it by hand when you want to ensure that the CSS gets reloaded.

RichieHindle
this is a common approach - see also http://stackoverflow.com/questions/438821/what-does-do-in-a-css-link
Paul Dixon
but this puts heavy load on your servers as now the client loads the css everytime as the ?random=xxx is differnet all the time. As browsers aren't supposed to cache urls with variables (although IE and FF do)
jitter
Well that isn't supposed to work. Browsers understand the URL and shouldn't cache the ?asdasd=adssad part.
jitter
@jitter: If I have /viewCustomer?custId=1 and /viewCustomer?custId=2 I certainly don't want the browser to treat those two URLs as the same page and cache only a single copy of it. What you are proposing means that if I visit /viewCustomers?custId=1 I could end up with a cached copy of /viewCustomers?custId=9 because it is newer than the one for custId=1. AFAIK browsers always have (and hopefully always will) treat each entire unique URL (including the query string) as a unique resource that is to be cached (ignoring any other cache directives and the caching policies of the specific browser).
Grant Wagner
+2  A: 

You can try editing the server etags: http://developer.yahoo.com/performance/rules.html#etags

But the preferred method is probably to rename your CSS file, such as with the date or the build number, so that users will always have the latest.

Jourkey
+2  A: 

Check this solution instead of using xx.css?rand=213213213

What is an elegant way to force browsers to reload cached CSS/JS files?

Or google for "auto versioning" plus adding javascript or css. Or "automatic asset versioning"

It uses an automatic approach which changes the path of the URL part no by appending get variables.

jitter