PageTransitionEvent.persisted何时评估为true?

10

我试图检测当前页面是从缓存加载还是新的副本。

我在body标签上注册了onPageShow回调函数。 我可以看到它被触发,但我无法产生一个事件.persisted实际为真的情况。

我甚至将Firefox置于脱机模式,并在网络选项卡中看到响应从缓存获取,但事件.persisted仍然为false。


你尝试在不同的浏览器上测试过吗?同时,尝试返回页面 - 它应该从缓存中加载。例如,如果您在body标签上注册了onpageshow事件,然后单击某个链接以在同一选项卡中打开另一页,然后导航回原始页面。它是否触发? - Sebastian Kaczmarek
试试这个:https://dev59.com/7XVC5IYBdhLWcg3wixs0#265125 - Stanley Ko
5个回答

5

嗯,我可以确认var isCached = performance.getEntriesByType("navigation")[0].transferSize === 0;在Chrome上有效。值得一试。 另外,正如其他人建议的那样,您可能需要查看这个示例如何使用JavaScript检测是否在缓存页面上


3

来自Google图书

在这里输入图片描述

这在Mozilla上完美运行。

请尝试以下代码:

<meta http-equiv="Cache-control" content="public">
...
<body onpageshow="onShow(event)" onpagehide="onHide(event)">
    <div  >
            <a href='/new.html' >Next page</a>
    </div>
<script>
function onShow(event) {
       if (event.persisted) {
                alert('Persisted...');
       }
}
function onHide(event) {
        if(event.persisted) {
                alert("Persisted")
        }
}
</script>
</body>

在new.html添加任何代码,空白页面也可以。
然后使用浏览器返回。您将得到警告消息。
注意: 使用域名或ngrok。本地缓存无效。
重新加载不会触发持续。我仅尝试了页面显示/隐藏。
我跳过了其他答案,以确定是否有缓存。

在Mozilla中可以工作,但在Chrome或IE11中无法工作。 - lofihelsinki
@lofihelsinki 提出了具体的问题,要求使用 Mozilla。我会在 Chrome 中检查并回复您。 - Viswanath Lekshmanan

3

IE11具有window.performance.getEntriesByType('navigation'),但没有transferSize。但是,如果页面来自浏览器缓存,则似乎会省略connectEnd

扩展@subhendu-kundu的答案,这也适用于IE11。

<script>

  window.addEventListener('pageshow', function(event) {

    if (window.performance) {
      var navEntries = window.performance.getEntriesByType('navigation');
      if (navEntries.length > 0 && typeof navEntries[0].transferSize !== 'undefined') {

        if (navEntries[0].transferSize === 0) {
          // From cache
        }

      } else if (navEntries.length > 0) {

        // IE11 seems to leave this completely if loaded from bfCache
        if (!navEntries[0].connectEnd) {
          // From cache
        }

      }
    }

  });

</script>

-1

好的,我可以建议您禁用浏览器缓存并检查提取代码块的大小。 您可以从浏览器本身禁用缓存..(我只是提出我的看法)。

enter image description here


1
“我甚至将Firefox设置为离线模式,我看到响应是从缓存中获取的…” - Adriano Repetti
1
并没有真正提供任何回答该问题的方式。 - lofihelsinki

-1

我不确定我是否正确理解了你的问题,你想检查加载的页面是来自磁盘/内存缓存还是新的页面。如果我理解错了,请在下面评论。

我正在尝试检测当前页面是否从缓存加载还是新的副本。

为此,您可以打开浏览器的开发人员工具并检查网络选项卡,如果页面是从缓存中加载的,则会显示指示(from cache)

Chrome支持此功能,但对于火狐浏览器,我认为您应该安装Web Developer插件:https://addons.mozilla.org/en-US/firefox/addon/web-developer/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接