寫到這裡,我們已經認識了不少 Web API:從 Canvas 到各種裝置、分享、鎖定、互動,這些功能大多「能做什麼」。今天換個角度,談談「做得怎麼樣」——Performance API。 🧮 ⏱️
當網頁變得越來越複雜、動態,效能(Performance)不再只是感覺上的「快」或「慢」。我們需要更精確的數據,來回答:
Performance API 就是瀏覽器提供的一套工具,讓我們能量化這些問題,而不是憑感覺。
最常見、最基礎的方法:
const start = performance.now();
for (let i = 0; i < 1e6; i++) {
// 做一些計算
}
const end = performance.now();
console.log(`花費時間: ${(end - start).toFixed(2)} ms`);
比起 Date.now()
,它的解析度更高(小數毫秒),也不會因為系統時間被調整而受影響。
瀏覽器會把「載入階段」、「首次繪製」與「資源下載」的時間軸以 Performance Timeline 暴露出來。
// 1) 導覽/載入階段
const nav = performance.getEntriesByType("navigation")[0];
console.table(nav);
// 2) 首次繪製
console.table(performance.getEntriesByType("paint"));
// 3) 資源載入
console.table(performance.getEntriesByType("resource"));
這些欄位來自 PerformanceNavigationTiming,屬於 Navigation Timing Level 2。
0
。DOMContentLoaded
事件時間。load
事件起訖。navigate
/ reload
/ back_forward
。performance.getEntriesByType('paint')
會回傳 PerformancePaintTiming
陣列:
每個靜態資源皆為 PerformanceResourceTiming
:
img
、script
、link
…LCP(Largest Contentful Paint)衡量「視窗中最大的內容」完成繪製的時間,是 Core Web Vitals 的核心指標之一。它不會出現在 navigation
/ paint
/ resource
清單,必須用 PerformanceObserver
監聽。
const po = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
// entry 為 LargestContentfulPaint
console.log('LCP candidate:', entry.startTime, entry.size, entry);
}
});
po.observe({ type: 'largest-contentful-paint', buffered: true });
// 建議在首次互動(如 click / keydown)後停止觀察,凍結最終 LCP:
addEventListener('pointerdown', () => po.disconnect(), { once: true });
addEventListener('keydown', () => po.disconnect(), { once: true });
buffered: true
可補抓頁面早期的紀錄。disconnect()
,可拿到更穩定的最終值。Performance API 也允許開發者自訂「錨點」:
performance.mark("start-task");
// 執行某個任務
performance.mark("end-task");
performance.measure("task-duration", "start-task", "end-task");
console.log(performance.getEntriesByType("measure"));
performance.getEntriesByType("measure")
回傳陣列,元素為 PerformanceMeasure
物件,包含:
task-duration
)。measure
。end - start
,毫秒)。例如:
[
{
"name": "task-duration",
"entryType": "measure",
"startTime": 123.4,
"duration": 156.7
}
]
這讓我們可以很精確地追蹤「特定任務」到底花多久。
Performance API 的核心價值在於「量化」:
performance.now()
:高解析度時間量測。PerformanceObserver
監聽的關鍵體驗指標。有了這些數據,效能優化就不再是憑直覺,而是有數據、有依據的工程。🚀
👉 歡迎追蹤這個系列,我會從 Canvas 開始,一步步帶你認識更多 Web API 🎯