PerformanceNavigationTiming: redirectCount 屬性

Baseline 已廣泛支援

此功能已成熟,並且適用於多種裝置和瀏覽器版本。自 2021 年 10 月以來,它已在所有瀏覽器中可用。

只讀屬性 redirectCount 返回一個數字,表示當前瀏覽上下文中,自上一次非重定向導航以來發生的重定向次數。

頁面上的重定向次數越多,頁面載入時間就越長。為了提高網頁的效能,請避免多次重定向。

可以使用 redirectStartredirectEnd 屬性來衡量重定向時間。請注意,對於跨域重定向,它們將返回 0

請注意,客戶端重定向,例如 <meta http-equiv="refresh" content="0; url=https://example.com/"> 不在此範圍內。

redirectCount 屬性可以具有以下值

  • 一個數字,表示當前瀏覽上下文中,自上一次非重定向導航以來發生的重定向次數。
  • 如果重定向是跨域的,則為 0

示例

記錄帶有重定向的條目

redirectCount 屬性可用於檢查是否存在一個或多個重定向。如果條目名稱和重定向時間可用,我們將記錄它們。

使用 PerformanceObserver 的示例,它會在瀏覽器效能時間線中記錄新的 navigation 效能條目時通知您。使用 buffered 選項可以訪問觀察者建立之前的條目。

js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    const name = entry.name;
    const redirectCount = entry.redirectCount;
    const redirectTime = entry.redirectEnd - entry.redirectStart;
    if (redirectCount > 0) {
      console.log(`${name}: Redirect count: ${redirectCount}`);
      if (redirectTime > 0) {
        console.log(`${name}: Redirect time: ${redirectTime}ms`);
      }
    }
  });
});

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

使用 Performance.getEntriesByType() 的示例,它僅顯示在呼叫方法時瀏覽器效能時間線中存在的 navigation 效能條目。

js
const entries = performance.getEntriesByType("navigation");
entries.forEach((entry) => {
  const name = entry.name;
  const redirectCount = entry.redirectCount;
  const redirectTime = entry.redirectEnd - entry.redirectStart;
  if (redirectCount > 0) {
    console.log(`${name}: Redirect count: ${redirectCount}`);
    if (redirectTime > 0) {
      console.log(`${name}: Redirect time: ${redirectTime}ms`);
    }
  }
});

規範

規範
導航計時 Level 2
# dom-performancenavigationtiming-redirectcount

瀏覽器相容性

另見