Performance: mark() 方法

Baseline 已廣泛支援

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

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

mark() 方法會建立一個命名的 PerformanceMark 物件,該物件表示瀏覽器效能時間線中的一個高精度時間戳標記。

語法

js
mark(name)
mark(name, markOptions)

引數

name

一個代表標記名稱的字串。其名稱不能與已棄用的 PerformanceTiming 介面的某個屬性名稱相同。

markOptions 可選

一個用於為標記指定時間戳和其他元資料的物件。

detail 可選

要包含在標記中的任意元資料。預設為 null。必須是 結構克隆演算法 支援的。

startTime 可選

DOMHighResTimeStamp,用作標記時間。預設為 performance.now()

返回值

建立的 PerformanceMark 條目。

異常

示例

建立命名標記

以下示例使用 mark() 來建立命名的 PerformanceMark 條目。您可以建立多個同名標記。您還可以為它們賦值,以便擁有對已建立 PerformanceMark 物件的引用。

js
performance.mark("login-started");
performance.mark("login-started");
performance.mark("login-finished");
performance.mark("form-sent");

const videoMarker = performance.mark("video-loaded");

建立帶有詳細資訊的標記

效能標記是可配置的,可以使用 markOptions 物件,您可以在其中將附加資訊放入 detail 屬性中,該屬性可以是任何型別。

js
performance.mark("login-started", {
  detail: "Login started using the login button in the top menu.",
});

performance.mark("login-started", {
  detail: { htmlElement: myElement.id },
});

建立具有不同開始時間的標記

mark() 方法的預設時間戳是 performance.now()。您可以使用 markOptions 中的 startTime 選項將其設定為其他時間。

js
performance.mark("start-checkout", {
  startTime: 20.0,
});

performance.mark("login-button-pressed", {
  startTime: myEvent.timeStamp,
});

保留名稱

注意,為了向後相容,不能使用已棄用的 PerformanceTiming 介面中的名稱。以下示例會丟擲錯誤:

js
performance.mark("navigationStart");
// SyntaxError: "navigationStart" is part of
// the PerformanceTiming interface,
// and cannot be used as a mark name

規範

規範
使用者計時
# dom-performance-mark

瀏覽器相容性