浏览器缓存

2023 年 9 月 15 日

浏览器缓存是一种将网页资源临时存储在用户设备上的技术,以便在用户再次访问同一网页或者其他需要相同资源的网页时提供更快的加载速度。深入理解浏览器缓存涉及以下几个关键方面:

  1. 缓存位置: 浏览器缓存可以分为多个位置,包括内存缓存和磁盘缓存。内存缓存速度更快,但容量更小,通常用于存储频繁访问的资源,而磁盘缓存则更适合长期存储。

  2. 强缓存与协商缓存: 浏览器缓存通常分为强缓存和协商缓存两种方式。强缓存是指浏览器在不向服务器发送请求的情况下直接从本地缓存中获取资源,而协商缓存是指浏览器在本地缓存过期后向服务器发送请求,根据服务器返回的响应决定是否使用缓存。

综上所述,深入理解浏览器缓存需要了解缓存的位置、控制、类型、策略以及清除方法等方面的知识,这些知识可以帮助网站开发者优化网页加载性能,并提升用户体验。

强缓存

Expires

In HTTP/1.0, freshness used to be specified by the Expires header.
在 HTTP/1.0 中,新鲜度过去由  Expires  标头指定。

The Expires header specifies the lifetime of the cache using an explicit time rather than by specifying an elapsed time.
Expires  标头使用显式时间而不是指定经过的时间来指定缓存的生命周期。

However, the time format is difficult to parse, many implementation bugs were found, and it is possible to induce problems by intentionally shifting the system clock; therefore, max-age — for specifying an elapsed time — was adopted for Cache-Control in HTTP/1.1.
然而,时间格式难以解析,发现了许多实现错误,并且有可能通过故意移动系统时钟来引发问题;因此, max-age (用于指定经过的时间)在 HTTP/1.1 中被采用为  Cache-Control 。

Expires: Tue, 28 Feb 2022 22:22:22 GMT

首选 max-age

协商缓存

Stale responses are not immediately discarded. HTTP has a mechanism to transform a stale response into a fresh one by asking the origin server. This is called validation, or sometimes, revalidation.
过时的响应不会立即被丢弃。 HTTP 有一种机制,可以通过询问源服务器将陈旧的响应转换为新的响应。这称为验证,有时也称为重新验证。

协商缓存针对的是过时的响应

IF-Modified-Since,Last-Modified

The server can obtain the modification time from the operating-system file system, which is relatively easy to do for the case of serving static files.
服务器可以从操作系统文件系统中获取修改时间,这对于提供静态文件的情况来说相对容易做到。
However, there are some problems; for example, the time format is complex and difficult to parse, and distributed servers have difficulty synchronizing file-update times.
但也存在一些问题;例如,时间格式复杂且难以解析,分布式服务器难以同步文件更新时间。

ETag、IF-None-Match

HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1024
Date: Tue, 22 Feb 2022 22:22:22 GMT
ETag: "33a64df5"
Cache-Control: max-age=3600

<!doctype html>

The server will return 304 Not Modified if the value of the ETag header it determines for the requested resource is the same as the If-None-Match value in the request.
如果服务器为请求的资源确定的  ETag  标头的值与请求中的  If-None-Match  值相同,则返回  304 Not Modified 。

But if the server determines the requested resource should now have a different ETag value, the server will instead respond with a 200 OK and the latest version of the resource.
但是,如果服务器确定请求的资源现在应该具有不同的  ETag  值,则服务器将使用  200 OK  和最新版本的资源进行响应。