PerformanceNavigationTiming: type 属性

Baseline 已广泛支持

此功能已成熟,并且适用于多种设备和浏览器版本。自 2021 年 10 月以来,它已在所有浏览器中可用。

只读属性 type 返回导航的类型。

您可以使用此属性对导航计时数据进行分类,因为每种类型都有不同的性能特征。用户在网站上前后导航可能比首次导航或提交表单等用户体验更快。用户往返于网站时,体验可能比首次访问或提交表单的用户更快。

例如,如果您的网站频繁提供新内容,您可能希望使用 Fetch API 或类似方法刷新该内容,并避免用户始终需要重新加载整个页面。"reload" 类型可以帮助您找到经常重新加载的页面。

type 属性可以具有以下值:

通过单击链接、在浏览器地址栏中输入 URL、提交表单,或通过除下面列出的 reloadback_forward 以外的脚本操作启动的导航。

"reload"

通过浏览器的重新加载操作、location.reload() 或 Pragma 指令(如 <meta http-equiv="refresh" content="300">)进行的导航。

"back_forward"

通过浏览器的历史记录遍历操作进行的导航。

示例

记录重新加载导航

可以使用 type 属性来检查导航是否为 reload 类型。您可以将这些 reload 条目收集到服务器端端点,以确定您网站的哪些页面重新加载的次数最多,或者收集所有导航类型并确定例如有多少百分比的用户进行后退和前进导航。

使用 PerformanceObserver 的示例,它会在浏览器性能时间线中记录新的 navigation 性能条目时通知您。使用 buffered 选项可以访问观察者创建之前的条目。

js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.type === "reload") {
      console.log(`${entry.name} was reloaded!`);
      console.log(entry);
    }
  });
});

observer.observe({ type: "navigation", buffered: true });

使用 Performance.getEntriesByType() 的示例,它仅显示在调用方法时浏览器性能时间线中存在的 navigation 性能条目。

js
const entries = performance.getEntriesByType("navigation");
entries.forEach((entry) => {
  if (entry.type === "reload") {
    console.log(`${entry.name} was reloaded!`);
    console.log(entry);
  }
});

规范

规范
导航计时 Level 2
# dom-performancenavigationtiming-type

浏览器兼容性