You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PerformanceObserver的脚本本地正常,部署到服务器后失效求助

问题分析与修复方案

你的脚本在本地正常运行,但部署到服务器后Chrome浏览器下无任何反应,核心原因是Chrome的**往返缓存(BF Cache)**机制,结合PerformanceObserver的触发条件差异导致的。

关键原因

  • 本地环境中,Chrome默认在打开DevTools时禁用BF Cache,页面后退/前进会重新加载,PerformanceObserver能正常捕获back_forward类型的导航条目。
  • 服务器环境下,Chrome启用BF Cache:页面后退/前进时直接从内存恢复,不会重新执行脚本初始化逻辑,PerformanceObserver可能未完成注册,或无法捕获已触发的导航事件;同时BF Cache恢复时不会触发常规的导航类性能条目。

修复方案

方案1:改用pageshow事件监听BF Cache恢复

BF Cache恢复页面时会触发pageshow事件,通过event.persisted可判断页面是否从缓存恢复,这是更可靠的监听方式:

window.addEventListener('pageshow', (event) => {
  if (event.persisted) {
    const data = document.querySelector(".h1");
    data.textContent = "hello";
    setTimeout(() => {
      window.location.reload();
    }, 2000);
  }
});

方案2:优化PerformanceObserver配置

添加buffered: true参数,允许PerformanceObserver捕获脚本注册前已发生的性能条目,同时确保脚本在页面早期执行:

console.log(1);

const observer = new PerformanceObserver(list => {
    console.log(2);
    list.getEntries().forEach(entry => {
       if (entry.type === "back_forward") {
           const data = document.querySelector(".h1");
           data.textContent = "hello";
           setTimeout(() => {
               window.location.reload();
           }, 2000);
       }
    });
});

console.log(3);

// 启用buffered模式,捕获已存在的导航条目
observer.observe({ type: "navigation", buffered: true });

方案3:临时禁用BF Cache(不推荐)

通过添加空的unload事件可以阻止Chrome使用BF Cache,但会降低页面加载性能,仅用于验证:

window.addEventListener('unload', () => {});

验证步骤

  1. 关闭Chrome DevTools(DevTools默认禁用BF Cache),执行后退/前进操作测试逻辑。
  2. 可通过chrome://flags/#back-forward-cache确认BF Cache处于启用状态(默认开启)。

内容的提问来源于stack exchange,提问作者Ivan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 09:31:43