简介
性能时间记录接口 (Performance Timeline Level 2)是hr-time-2的扩展,定义了(Performance)获取和存储性能信息的数据结构(PerformanceEntry)
扩展/定义对象
Performance
level 2 扩展了performance 3个获取PerformanceEntry性能数据的方法
数据结构
partial interface Performance {
PerformanceEntryList getEntries (); // filter by name and entryType
PerformanceEntryList getEntriesByType (DOMString type); // filter by name and type
PerformanceEntryList getEntriesByName (DOMString name, optional DOMString type); // filter by name, entryType, type
};
typedef sequence<PerformanceEntry> PerformanceEntryList;
基本使用
let entries1 = performance.getEntries({name: "entry_name", entryType: "mark"});
// type定义:
// frame, navigation : PerformanceFrameTiming, PerformanceNavigationTiming
// resource : PerformanceResourceTiming
// mark : PerformanceMark : performance.mark()
// measure : PerformanceMeasure : performance.measure()
// paint : PerformancePaintTiming : first-paint, first-contentful-paint
let entries2 = performance.getEntriesByType(type)
let entries3 = performance.getEntriesByName(name, type)
PerformanceEntry
PerformanceEntry 用于存储所有度量性能数据:具体记录了某一资源(如标签、navigation、渲染等)的performance信息,不同类型(entryType)的PerformanceEntry属性有所不同
数据结构
interface PerformanceEntry {
readonly attribute DOMString name; // 不唯一
// entryType定义:https://w3c.github.io/timing-entrytypes-registry/#registry
// 【注】有大小限制,是否是属于timeline事件
readonly attribute DOMString entryType;
readonly attribute DOMHighResTimeStamp startTime; // 如果不设置从0开始
readonly attribute DOMHighResTimeStamp duration; // 第一次记录与最后一次记录的时间差
[Default] object toJSON();
};
entryType类型
| entryType | specification |
|---|---|
| mark, measure | user-timing |
| navigation | navigation-timing |
| resource | resource-timing |
| longtask | longtask |
| paint | paint-timing |
| element | element-timing |
| event, first- input | event-timing |
| layout-shift | layout-instability |
| largest-contentful-paint | largest-contentful-paint |
PerformanceObserver
PerformanceObserver提供了一个缓冲的性能检测接口,用于在浏览器性能时间轴监测性能度量事件。
- 避免了轮询检测浏览器时间轴
- 减少了重复的检测逻辑
- 减少了资源的竞态条件(race condition)
数据结构
interface PerformanceObserver {
constructor(PerformanceObserverCallback callback);
undefined observe (optional PerformanceObserverInit options = {});
undefined disconnect ();
PerformanceEntryList takeRecords(); // return copy of observer buffer
[SameObject] static readonly attribute FrozenArray<DOMString> supportedEntryTypes;
};
基本使用
// 以测量User-Timing为例
const userTimeObser = new PerformanceObserver(list => {
list.getEntries().map(({name, entryType, startTime, duration }) => {})
userTimeObser.disconnect()
})
userTimeObser.observe({entryTypes: ["mark", "measure"]});
userTimeObser.takeRecords()
// ["element", "event", "first-input", "largest-contentful-paint", "layout-shift", "longtask", "mark", "measure", "navigation", "paint", "resource"]
PerformanceObserver.supportedEntryTypes