Asking browsers to cache as aggressively as possib

2019-01-16 10:26发布

This is about a web app that serves images. Since the same request will always return the same image, I want the accessing browsers to cache the images as aggressively as possible. I pretty much want to tell the browser

Here's your image. Go ahead and keep it; it's really not going to change for the next couple of days. No need to come back. Really. I promise.

I do, so far, set

Cache-Control: public, max-age=86400
Last-Modified: (some time ago)
Expires: (two days from now)

and of course return a 304 not modified if the request has the appropriate If-Modified-Since header.

Is there anything else I can do (or anything I should do differently) to get my message across to the browsers?

The app is hosted on the Google App Engine, in case that matters.

7条回答
\"骚年 ilove
2楼-- · 2019-01-16 11:02

You can do better. 304s are still a HTTP request/response. Though the image is not downloaded again, the latency can be killing.

If you can include a version identifier in your image names, you can set the max-age to 2 years. That way, you prevent 304s. If the image ever changes, you update the version identifier thereby changing the file name. This ensures that the browser will issue a fresh request.

It needs some changes to your project structure. The version identifier can be the SVN revision number when the image was last updated, and can be auto-generated at build time. You'd also need to update the html, so if you have a logical mapping between image name and image path, your job would be easier.

Images are rarely updated, so you could also follow a manual approach if you can't automate what I described above. The trick is to only add new images, never modify them.

查看更多
登录 后发表回答