# 前进后退缓存（bfcache）

> 前进后退缓存如何从内存恢复整个页面、哪些监听器和响应头会让页面在各引擎失去资格，以及 notRestoredReasons 如何报告原因。

前进后退缓存（bfcache）在用户离开时保存页面快照，让后退或前进导航可以即时恢复页面。快照包含 JavaScript 堆和未完成操作的状态。恢复时不必重建文档。JavaScript 在缓存期间暂停，恢复后继续执行，并非永久跳过。能否缓存取决于浏览器及页面状态（[Back/forward cache](https://web.dev/articles/bfcache)，web.dev）。

## 工作原理

离开页面时，浏览器会冻结页面，暂停定时器和待处理的 Promise，但不取消它们。文档会在内存中保留一段有限的时间。后退或前进回到该条目时页面原地解冻；`pageshow` 以 `persisted === true` 触发，`load` 事件不触发。如果浏览器已移除缓存页面（内存压力、时间上限或某个阻碍项），该导航就是一次普通加载（[Back/forward cache](https://web.dev/articles/bfcache)，web.dev）。当前 Chrome、Firefox 和 Safari 均包含 bfcache，但资格规则不同。

### 什么让页面失去资格

- 避免使用 `unload` 监听器。导航清理优先使用 `pagehide`，但不能靠它保存关键状态：移动端结束浏览器进程时可能不触发该事件（[pagehide](https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event)，MDN）。
- `Cache-Control: no-store` 控制 HTTP 缓存。Chrome 在额外限制下也允许部分此类页面进入 bfcache；认证状态变化会使它们被移出缓存，使用 WebSocket、WebTransport 或 WebRTC 也可能阻止缓存。不要为了缓存资格删除保护敏感内容的响应头（[Chrome 的 no-store 策略](https://developer.chrome.com/docs/web-platform/bfcache-ccns)，Chrome for Developers）。
- 活跃连接和事务可能影响缓存资格。通过 DevTools 检查实际导航，不要把执行了清理回调当成成功保证（[Test back/forward cache](https://developer.chrome.com/docs/devtools/application/back-forward-cache)，Chrome for Developers）。

### 读取页面未被恢复的原因

先检查导航条目是否提供 `notRestoredReasons`。有报告时，它解释历史导航未恢复页面的原因。`null` 不能证明恢复成功：普通导航及部分历史条目都可能没有报告。恢复是否实际发生，应观察 `pageshow.persisted`（[notRestoredReasons](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/notRestoredReasons)，MDN；[恢复事件](https://web.dev/articles/bfcache)，web.dev）。

### 支持位置

各引擎都有 bfcache：Safari 和 Firefox 已有十余年，Chrome 在 96 版本加入支持（[Back/forward cache](https://web.dev/articles/bfcache)，web.dev）。可观察的差异在于上面的资格规则，以及只有 Chromium 暴露的 `notRestoredReasons`。

### 与 Service Worker 和 Core Web Vitals 的关系

bfcache 恢复完全不经过 Service Worker 和 HTTP 缓存，Core Web Vitals 工具会把这次恢复计为独立页面访问，LCP 接近零，这正是 bfcache 资格能直接改善现场指标的原因。在 `pageshow` 处理器中检查 `event.persisted`，并刷新敏感状态，例如已经登出的会话、过期的购物车合计。恢复时不会触发 `load`，不能靠它刷新。

## 示例

bfcache 是文档级特性，示例代码要放在页面中运行，不能放在 Service Worker 中。

### 恢复时刷新过期状态

`pageshow` 在首次加载和恢复时都运行；`persisted` 区分两者。处理函数重新检查会话并重新获取需要保持最新的数据，而不重新加载页面。

```js
window.addEventListener('pageshow', (event) => {
  if (!event.persisted) return; // 普通加载：load 处理函数已经运行过
  refreshSession();
  refreshCartTotal();
});

window.addEventListener('pagehide', () => {
  closeLiveConnection(); // 应用清理；普通导航也需要释放连接
});
```

`refreshSession`、`refreshCartTotal` 和 `closeLiveConnection` 是需要自行实现的应用函数。在 `pageshow` 中按需重连。`pagehide.persisted` 为真只说明浏览器打算缓存，不保证最终缓存成功（[页面生命周期事件](https://web.dev/articles/bfcache)，web.dev）。

### 从现场上报阻碍项

页面未从缓存恢复时，将 `notRestoredReasons` 发给分析系统，就能找出生产环境中的阻碍项，例如注册了 `unload` 的第三方脚本。

```js
function reportBfcacheBlockers() {
  const [nav] = performance.getEntriesByType('navigation');
  if (!nav || !('notRestoredReasons' in nav)) {
    return; // 无现场报告：通过 pageshow.persisted 检查恢复
  }
  if (nav.type === 'back_forward' && nav.notRestoredReasons) {
    navigator.sendBeacon('/analytics/bfcache', JSON.stringify(nav.notRestoredReasons));
  }
}
```

按 `nav.type === 'back_forward'` 过滤：其他导航类型上该属性虽然存在，但描述的不是页面本可改变的东西。

:::note
Chrome DevTools 的 Application > Background services > Back/forward cache 有一个 **Test back/forward cache** 按钮，它离开页面再返回，然后报告页面已恢复，或给出未能恢复的原因。原因分为三组：**Actionable**（可以修复，例如不再使用 `unload` 事件）、**Pending Support**（Chrome 尚未支持该功能）和 **Not Actionable**（页面无法控制的因素）（[Test back/forward cache](https://developer.chrome.com/docs/devtools/application/back-forward-cache)，developer.chrome.com）。
:::

:::note
2026 年 11 月 18 日更正：修正 JavaScript 恢复执行、诊断报告可为空、退出事件不可靠，以及 Chrome 有条件允许 no-store 页面缓存的说明。本次为文档核对，并非新增设备实测。
:::

## 另请参阅

- [Back/forward cache](https://web.dev/articles/bfcache)（web.dev）
- [Test back/forward cache](https://developer.chrome.com/docs/devtools/application/back-forward-cache)（developer.chrome.com）
- [PerformanceNavigationTiming: notRestoredReasons property](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/notRestoredReasons)（developer.mozilla.org）
- [Core Web Vitals（LCP、INP 与 CLS）](/zh/reference/performance/core-web-vitals/)
- [Speculation Rules API](/zh/reference/performance/speculation-rules/)
- [PerformanceObserver 与绘制计时](/zh/reference/performance/startup-performance/)