跳转至

浏览器缓存机制

一、为什么需要缓存

减少重复请求,加快页面加载,降低服务器压力。

二、强缓存

不发请求,直接用本地缓存。响应头:

1. Expires

Expires: Wed, 21 Oct 2025 07:28:00 GMT

绝对时间。缺点:客户端时间可能不准。

2. Cache-Control(优先)

Cache-Control: max-age=3600
Cache-Control: no-cache       // 不直接用,要协商
Cache-Control: no-store      // 不缓存
Cache-Control: public / private

max-age 是相对时间,更可靠。

强缓存命中:200 (from disk cache) / (from memory cache)

三、协商缓存

强缓存过期,发请求问服务器"资源变了没"。

1. Last-Modified / If-Modified-Since

第一次响应:

Last-Modified: Wed, 21 Oct 2025 07:28:00 GMT

下次请求:

If-Modified-Since: Wed, 21 Oct 2025 07:28:00 GMT

没变返回 304 Not Modified,变了返回新资源 200

2. ETag / If-None-Match(更精确)

ETag: "abc123"

下次请求:

If-None-Match: "abc123"

ETag 是资源内容的哈希,比 Last-Modified 精确到秒更准。

四、缓存决策流程

flowchart TD
    A[请求资源] --> B{强缓存未过期?}
    B -- 是 --> C[直接用本地缓存]
    B -- 否 --> D[发协商请求]
    D --> E{资源变了?}
    E -- 没变 --> F[304 用缓存]
    E -- 变了 --> G[200 返回新资源]

五、实践建议

  • HTML:Cache-Control: no-cache,每次协商。
  • CSS / JS:内容带 hash(app.abc123.js),长缓存 max-age=31536000
  • 图片:长缓存。
  • 用户头像等动态内容:短缓存或 no-store。

高频追问

  • memory cache vs disk cache:内存缓存更快,但标签页关闭就没;磁盘缓存持久。
  • 强制刷新(Ctrl+F5)跳过所有缓存。