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

Chrome中用户回退页面时触发函数的问题及解决方案需求

解决Chrome回退页面时加载Spinner无法自动隐藏的问题

问题根源

Chrome新版中,从长加载页面回退时,页面会被存入bfcache(前后退缓存),这时候之前监听popstate事件的逻辑会失效;而Firefox对bfcache的处理逻辑不同,因此没有这个问题。

可用解决方案

方案1:监听pageshow事件处理缓存恢复场景

直接监听pageshow事件,判断页面是否从缓存恢复,是的话就隐藏spinner:

$(window).on('pageshow', function(event) {
  // persisted为true表示页面从bfcache中恢复
  if (event.originalEvent.persisted) {
    loading.hide();
  }
});

方案2:结合历史状态标记精准捕捉回退动作

如果需要只在用户主动回退时触发,可以给当前页面的历史记录加个标记,回退时检测这个标记:

$(document).ready(function() {
  if (window.history && window.history.pushState) {
    // 给当前页面的历史记录添加自定义标识
    window.history.pushState({ isCurrentPage: true }, document.title);
    
    $(window).on('popstate', function() {
      // 回退触发时隐藏spinner
      loading.hide();
      // 重新添加状态标记,避免多次回退时失效
      window.history.pushState({ isCurrentPage: true }, document.title);
    });
  }
});

// 同时兼容bfcache恢复的情况
$(window).on('pageshow', function(event) {
  if (event.originalEvent.persisted) {
    loading.hide();
  }
});

注意点

  • pageshow事件在页面首次加载和从缓存恢复时都会触发,用persisted属性可以区分缓存恢复的场景。
  • 手动添加历史状态标记能避免其他触发popstate的场景干扰,确保只在回退时执行隐藏操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:05:16