I would recommend solving this by embracing HTTP caching by changing the Cache-Control
to no-cache
. The browser will then always check to see if there's a newer/different version but since media items have Etag headers, the browser won't download the data it again if it's the same version it has cached.
As for implementation, you can apply this to all media items by setting the MediaResponse.Cacheability
Sitecore setting to serverandnocache
. However I that would also put more load on your server since all images would also be uncached. To avoid that, you'll need to subclass MediaRequestHandler
and override SendMediaHeaders
:
protected override void SendMediaHeaders(Media media, HttpContext context)
{
base.SendMediaHeaders(media, context);
if (media.MimeType == "application/pdf") // Preferably a more specific descriminator
{
context.Response.Cache.AppendCacheExtension("no-cache");
}
}
Now for the detail.
In HTTP, the Cache-Control
response header tells the browser how to cache the request. Cache-Control: private, max-age=600
indicates that the response can be cached by the browser for 600 seconds.
After this time, the resource will be re-requested from the server. However, if identity information (Etag
or Last-Modified
) was included in the original request these will be sent with the new request, which indicates that "this is what I have cached". The server will either send back 204 Not modified
("what you have cached is fine"), or a new 200 OK
response with the content of the file.
Adding a no-cache
directive forces a validation request to occur each time, but since max-age
is also specified the browser will still fall back to the cached version if a 204
response is received.