PerformanceResourceTiming: connectEnd 屬性

Baseline 已廣泛支援

此功能已成熟,可跨多種裝置和瀏覽器版本使用。自 2017 年 9 月以來,它已在瀏覽器中提供。

注意:此功能在 Web Workers 中可用。

只讀屬性 connectEnd 返回瀏覽器完成與伺服器建立連線以檢索資源的 timestamp。時間戳值包括建立傳輸連線的時間間隔,以及 TLS 握手和 SOCKS 身份驗證等其他時間間隔。

connectEnd 屬性可以具有以下值

  • 一個 DOMHighResTimeStamp,表示連線建立後的時間。
  • 如果資源是從快取中即時檢索的,則為 0
  • 如果資源是跨域請求且未使用 Timing-Allow-Origin HTTP 響應頭,則返回 0

示例

測量 TCP 握手時間

connectEndconnectStart 屬性可用於測量 TCP 握手發生所需的時間。

js
const tcp = entry.connectEnd - entry.connectStart;

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

js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    const tcp = entry.connectEnd - entry.connectStart;
    if (tcp > 0) {
      console.log(`${entry.name}: TCP handshake duration: ${tcp}ms`);
    }
  });
});

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

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

js
const resources = performance.getEntriesByType("resource");
resources.forEach((entry) => {
  const tcp = entry.connectEnd - entry.connectStart;
  if (tcp > 0) {
    console.log(`${entry.name}: TCP handshake duration: ${tcp}ms`);
  }
});

跨域計時資訊

如果 connectEnd 屬性的值為 0,則該資源可能是跨域請求。要允許檢視跨域時序資訊,需要設定 Timing-Allow-Origin HTTP 響應頭。

例如,要允許 https://mdn.club.tw 檢視時序資源,跨域資源應傳送

http
Timing-Allow-Origin: https://mdn.club.tw

規範

規範
資源時序
# dom-performanceresourcetiming-connectend

瀏覽器相容性

另見