This rule is triggered when PageSpeed Insights detects that your server response does not contain an explicit cache header or that some resources are specified to be cached only for a short period of time.

Overview

Browser caching of static resources can save users time if they visit your site multiple times. Cache headers should be applied to all cacheable static resources, not just to a small number of static resources (for example, pictures). Cacheable resources include JS and CSS files, image files, and other binary object files (media files, PDF files, and so on). Typically, HTML is not a static resource and should not be considered a cacheable resource by default. You should consider which caching policies apply to the HTML of your website.

Recommendations

为您的服务器启用浏览器缓存。静态资源应该至少有一周的缓存有效期。广告或小部件这类的第三方资源也应该至少有一天的缓存有效期。对于所有可缓存资源,我们建议您进行以下设置:

  • ExpiresSet it to a future date, at least one week and at most one year (we tend to setExpires,而不设置Cache-Control: max-age,因为前者受支持的范围更为广泛)。请勿将其设为超过一年的将来日期,因为这样就违反了RFC准则。
  • If you know exactly when the resource will change, you can set a shorter expiration date. However, if you think the resource "may be about to change" but do not know the exact time, you should set a longer expiration date and use URL fingerprints (as described below).

Expires and Cache-Control: max-age header

这些标头用于指定相应时间段,浏览器可在指定的这段时间内使用已缓存的资源,而无需查看网络服务器是否提供了新版资源。这些缓存标头功能强大,没有任何应用条件限制。在设置这些标头并下载资源后,浏览器不会为资源发出任何GET请求,除非过期日期到期或达到时间最大值,亦或是用户清除了缓存。

Last-Modifed和ETag标头

这些标头可用于指定浏览器应如何确定用于缓存的文件是否相同。在Last-ModifiedThe date is specified in the header, while the date specified in theETag标头中指定的则可以是唯一标识资源的任意值(通常为文件版本或内容哈希值)。Last-Modified是功能“较弱”的缓存标头,因为浏览器会使用试探法来确定是否需要从缓存中抓取内容。

With these headers, browsers can effectively update their cached resources by issuing a conditional GET request when the user explicitly reloads the page. A conditional GET request does not return a complete response unless you change the resource on the server side, so such a request has less latency than a complete GET request.

我应使用哪个缓存标头?

对于所有可缓存资源,指定一个ExpiresCache-Control max-ageAnd aLast-ModifiedETag至关重要。您没必要同时指定ExpiresAndCache-Control: max-age;或同时指定Last-ModifiedETag

Use URL fingerprints

对于偶尔发生变化的资源,我们可以让浏览器缓存相应的资源,直到该资源在服务器上出现变化,而服务器则在此时通知浏览器有新版本可用。我们可以通过为每个版本的资源指定一个唯一网址来实现这一目的。例如,假定我们有一个名为“my_stylesheet.css”的资源。我们可以将文件重命名为“my_stylesheet_fingerprint.css”。当资源发生变化时,其指纹就会发生变化,对应的网址也会随之更改。网址一经更改,系统就会强制浏览器重新抓取资源。通过指纹,我们甚至可以为变化更为频繁的资源设置将来的过期日期。

指纹识别的常用方法是使用对文件内容的哈希值进行编码的128位十六进制数。

另一个策略是直接为新版应用创建新版目录,然后为版本目录中的各个版本放置所有资源。这样做的缺点是,如果各个版本中的资源未发生变化,则其网址将仍会更改以强制重新下载。使用内容哈希值不会遇到该问题,但这种方法稍微复杂一些。

 

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under theApache 2.0 License. For details, see our Site Policies.