tags:

views:

442

answers:

2

Hello. Somewhere in CSS:

.button {
    background: url(../Images/button.png);
}

Problem: for performance reason all static content has expiration headers and is cached by browser. When image changes user must refresh cache (Ctrl+F5 in IE). I want images to be cached, but when necessary they must be automatically reloaded.

Question: is next approach 'valid'?

.button {
    background: url(../Images/button.png?v=1234);
}

where v=1234 is version of my site. I do not know whether it is 100% valid to write such things in CSS and I do want browsers to still cache images if version is the same. Do all modern browsers correctly cache data with URL parameters part?

Thanks.

+2  A: 

That looks like a good approach to me, it'll work fine in CSS in modern browsers - the browser will look at the address of the image (including the ?v=1234), see that it's not cached, and send a fresh request.

Dominic Rodger
What is the reason for the down vote?
rahul
That's not entirely true .. IE is the most anoying one, being actually able to ignore hashed links and cache-control headers .. Altought it's the "best" approach ..
yoda
it may be related to the comment on the original question "I believe that doesn't work on every browser", it seems a valid approach if enough browsers do support it
Rich Seller
I tested slightly this solution under IE8 and FF3.5. The only pity thing is when 'a.gif?v=1' changes to 'a.gif?v=2' browser do not use ETag (ETag is the same for v=2 because image wasn't actually changed) and fetches image from the server :(. But it works.
Roman
A: 

This is discussed in rule 3 of High Performance Web Sites: "Add an Expires or a Cache-Control Header". One of the approaches recommended is to version the files rather than the site.

From the accompanying blog:

Keep in mind, if you use a far future Expires header you have to change the component's filename whenever the component changes. At Yahoo! we often make this step part of the build process: a version number is embedded in the component's filename, for example, yahoo_2.0.6.js.

Rich Seller
I do such file version naming (e.g. yahoo_2.0.6.js) with JavaScript and CSS files, but it's far more difficult to me to rename all images that have been changed, that's why I want some approach that doesn't require image file name to be changed. There is another downside with '?1234' approach - new version of site invalidates all images, even not modified, but at least this is less painful in maintenance.
Roman