User generated images on my site are served up by giving them a src
like this:
userImage.ashx?id={UserId}&type=avatar
In the response from the ashx
file, I set the etag header. When a user uploads a new image, the etag changes.
If the browser has a file cached with an etag, it should send a request to the server with the If-None-Match
header set to that etag whenever it needs to display that file. If the cached etag is the same as the current etag on the server, the server responds with Not Modified - 304
. If the etag is different, the server responds with OK - 200
and starts sending the new file.
This is how it should work in theory. However, I have found that for some browsers (firefox and IE, untested on others) this is not the case. If the user navigates to a new page with cached, etagged images, these browsers simply use the image out of their cache without making a request. If the user then refreshes the page, the browser sends a request with the If-None-Match
header set.
So my problem is this: a user updates one of their images, then navigates to a page displaying the image. Until the user presses refresh
, the cached image will be displayed, even though it has a different etag to the new image. When the user presses refresh, the browser does a request with the If-None-Match
header set, which triggers the server to send the new image.
Is it possible to fix this?
Example 200 response header:
Status=OK - 200
Date=Thu, 27 Oct 2011 14:37:31 GMT
Server=Microsoft-IIS/6.0
X-Powered-By=ASP.NET
X-AspNet-Version=4.0.30319
Transfer-Encoding=chunked
Cache-Control=public, max-age=86400
Etag="27/10/2011 13:23:30"
Content-Type=image/jpg
Example 304 header:
Status=Not Modified - 304
Connection=close
Date=Thu, 27 Oct 2011 14:39:12 GMT
Server=Microsoft-IIS/6.0
X-Powered-By=ASP.NET
X-AspNet-Version=4.0.30319
Cache-Control=public, max-age=86400
(Using last modfied date as etag as its more adaptable for later needs regarding compression etc.)
IIRC you can set how long a file is valid via the "Expires" header. So if you say "This file is valid for the next two days", the browser has no reason to contact your server.
max-age as given in your example does the same thing, basically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With