强缓存命中机制

浏览器强缓存命中时的完整流程

问题

当浏览器强缓存命中时,具体发生了什么?

解答

强缓存命中流程

浏览器发起请求

检查本地是否有缓存

   有缓存 → 检查是否过期(Expires / Cache-Control)

   未过期 → 直接读取本地缓存,不发送请求

返回 200 (from memory cache) 或 200 (from disk cache)

判断缓存是否过期

浏览器通过响应头判断缓存有效期:

# 方式一:Expires(HTTP/1.0)
# 指定绝对过期时间
Expires: Wed, 25 Dec 2024 12:00:00 GMT

# 方式二:Cache-Control(HTTP/1.1,优先级更高)
# max-age 指定相对过期时间(秒)
Cache-Control: max-age=31536000

两种缓存位置

// 强缓存命中时,资源可能来自两个位置:

// 1. memory cache(内存缓存)
// - 读取速度快
// - 页面关闭后清除
// - 通常缓存小文件、当前页面已加载的资源

// 2. disk cache(磁盘缓存)
// - 读取速度相对慢
// - 持久化存储
// - 通常缓存大文件、非当前页面资源

服务器配置示例

# Nginx 配置强缓存
location ~* \.(js|css|png|jpg|gif|ico)$ {
    # 缓存一年
    expires 1y;
    # 或使用 Cache-Control
    add_header Cache-Control "public, max-age=31536000, immutable";
}

验证强缓存命中

打开 DevTools → Network 面板:

Name          Status    Size
app.js        200       (from disk cache)
logo.png      200       (from memory cache)
  • Size 列显示 from disk cachefrom memory cache
  • Time 列显示 0ms 或极短时间
  • 没有实际网络请求发出

关键点

  • 强缓存命中时不会发送任何请求到服务器
  • Cache-Control: max-age 优先级高于 Expires
  • memory cache 快但临时,disk cache 慢但持久
  • 状态码仍显示 200,但 Size 列会标注缓存来源
  • 要更新强缓存资源,通常需要修改文件名(如添加 hash)