性能对象

yuhuo2024-04-11JavaScriptJavaScript对象

PerformanceObserver 类

1. 创建对象

/**
 * list: PerformanceObserverEntryList
 * o: PerformanceObserver
 */
var observer = new PerformanceObserver((list, o) => {
    // true
    console.log(observer == o);
    // 遍历性能条目 PerformanceEntry 对象
    for(let entry of list.getEntries()) {
        console.log(entry)
    }
});
observer.observe({ entryTypes: ["paint","resource"] });
observer.observe({ type: "largest-contentful-paint", buffered: true});

2. 静态属性

静态属性类型描述
supportedEntryTypesstring[]返回所有支持的性能条目类型

3. 对象方法

对象方法描述
observe(options: {entryTypes: string[]} | {type: string, buffered?: boolean, durationThreshold?: number })监听性能条目缓存器中新加的,指定类型的性能条目,触发构造函数中的回调函数
entryTypes:一次观察多种类型的性能条目
type:观察一种类型的性能条目
buffered:是否观察性能条目缓存器中已存在的数据(默认 false,即只观察新加的)
durationThreshold:事件延迟响应门槛毫秒时间(默认104),即响应延迟超过该门槛才会触发回调,只在 event 类型中有效
disconnect()停止观察
takeRecords(): PerformanceEntryList返回性能条目缓存器中的所有对象,并将其清空(没测出效果?)

PerformanceEntry 类

1. 对象属性

对象属性类型描述
namestring名称
entryTypestring性能条目类型
startTimenumber开始时间(自页面加载计起的毫秒数)
durationnumber耗时

2. 对象方法

对象属性描述
toJSON()转 JSON 对象

PerformancePaintTiming 类

条目类型为 paint,包含渲染事件信息,其 name 又分为:

  • first-paint(FP):第一个像素完成渲染;
  • first-contentful-paint(FCP):第一次内容完成渲染;
var entry = {
    entryType: "paint",
    name: "first-paint",
    startTime: 40.19999998807907, // FP时间
    duration: 0,
};
var entry = {
    entryType: "paint",
	name: "first-contentful-paint",
	startTime: 40.599999994039536, // FPC时间
    duration: 0,
}

LargestContentfulPaint 类

条目类型为 largest-contentful-paint,包含最大内容块渲染事件信息。

var entry = {
    entryType: "largest-contentful-paint",
    name: "",
    startTime: 504.09999999403954, // LCP时间
    duration: 0,
    size: 128482, // 内容大小
    renderTime: 0,
    loadTime: 504.09999999403954, // 内容加载时间
    firstAnimatedFrameTime: 0,
    id: "",
    url: "https://yh.com/img/bg.9bdf4f4a.jpg", // 内容链接
};

PerformanceNavigationTiming 类

条目类型为 navigation,包含文档加载相关指标信息。

var entry = {
    entryType: "navigation",
    name: "http://127.0.0.1:5500/topic/monitoring/index.html",
    duration: 210.2999999821186,  // 资源加载耗时
    initiatorType: "navigation", // 资源类型
    type: "reload", // 文档来源类型
    startTime: 0, // 开始时间
    unloadEventStart: 12.599999994039536, // 卸载旧文档事件开始时间
    unloadEventEnd: 12.599999994039536, // 卸载旧文档事件结束时间
    redirectStart: 0, // 第一个重定向开始时间
    redirectEnd: 0, // 最后一个重定向结束时间
    redirectCount: 0, // 重定向次数
    nextHopProtocol: "http/1.1", // 请求协议
    fetchStart: 1.5, // 请求开始时间
    domainLookupStart: 1.5, // DNS查询开始时间
    domainLookupEnd: 1.5, // DNS查询结束时间
    connectStart: 1.5, // TCP建立开始时间
    secureConnectionStart: 0, // HTTPS建立开始时间
    connectEnd: 1.5, // TCP建立完成时间
    requestStart: 4.9000000059604645, // 请求发出时间
    responseStart: 9, // 响应接收开始时间
    firstInterimResponseStart: 0,
    responseEnd: 9.5, // 响应接收完成时间
    transferSize: 5638, // 接收数据大小,当为 0 时说明强制缓存,当不为 0 但 encodedBodySize 为 0 说明协商缓存
    encodedBodySize: 5338, // 响应体大小
    decodedBodySize: 5338, // 响应体解压大小
    responseStatus: 200, // 响应状态
    domInteractive: 20.599999994039536, // 文档加载解析完成时间,document.readyState=interactive
    domContentLoadedEventStart: 20.599999994039536, // DOMContentLoaded事件开始
    domContentLoadedEventEnd: 20.69999998807907, // DOMContentLoaded事件结束
    domComplete: 210.2999999821186, // 外部资源加载完成,document.readyState=complete
    loadEventStart: 210.2999999821186, // load事件开始
    loadEventEnd: 210.2999999821186, // load事件结束
    renderBlockingStatus: "non-blocking",
    deliveryType: "",
    workerStart: 0,
    serverTiming: [],
    activationStart: 0,
    criticalCHRestart: 0,
};

文档加载流程中各指标示意图:

PerformanceResourceTiming 类

条目类型为 resource,包含资源加载事件信息。

var entry = {
    entryType: "resource",
    name: "https://yh.com/img/bg.9bdf4f4a.jpg", // 资源名称
    startTime: 22.099999994039536, // 资源加载开始时间
    duration: 229.90000000596046, // 资源加载耗时
    initiatorType: "img",  // 资源类型
    deliveryType: "",
    nextHopProtocol: "", 
    renderBlockingStatus: "non-blocking",
    workerStart: 0,
    redirectStart: 0,
    redirectEnd: 0,
    fetchStart: 22.099999994039536,
    domainLookupStart: 0,
    domainLookupEnd: 0,
    connectStart: 0,
    secureConnectionStart: 0,
    connectEnd: 0,
    requestStart: 0,
    responseStart: 0,
    responseEnd: 252,
    firstInterimResponseStart: 0,
    transferSize: 0,
    encodedBodySize: 0,
    decodedBodySize: 0,
    responseStatus: 0,
    serverTiming: [],
};

PerformanceMark 类

条目类型为 mark,包含时间戳标记信息。

var entry = {
    entryType: "mark",
    name: "标记名称",
    detail: "标记说明",
    startTime: 23.400000005960464,
    duration: 0,
};

创建对象

// 通过构造函数创建,不会加入到性能条目缓存器中
// 故无法通过 PerformanceObserver 或 performance.getEntries() 获取
// PerformanceMark(name: string, options?: {detail?: string, startTime?: number})
let mark1 = new PerformanceMark("one");
let mark2 = new PerformanceMark("two", { detail: "二", startTime: 222 });

// 通过 performance.mark() 创建,参数同构造函数,加入性能条目缓存器
let mark3 = performance.mark("three");
let mark4 = performance.mark("four", { detail: "四", startTime: 444 });

PerformanceMeasure 类

条目类型为 measure,包含时间戳测量信息。

var entry = {
    entryType: "mark",
    name: "测量名称",
    detail: "测量说明",
    startTime: 200,
    duration: 50,
};

创建对象

// 只能通过 performance.measure() 创建,没有构造函数
// 测量2个mark之间的时间差
performance.mark("one", { startTime: 250 });
performance.mark("two", { startTime: 300 });
let measure1 = performance.measure("apple", "one", "two");

// 测量2个指定时间戳之间的时间差
let measure2 = performance.measure("banana", { detail: "测量说明", start: 100, end: 300 });

PerformanceEventTiming 类

条目类型为 first-input,包含用户首次页面操作的事件信息。

条目类型为 event,包含延迟响应超过门槛时间的事件信息。

比如说延迟响应门槛时间 104ms,点击按钮后延迟了 200ms 才响应,才会生成 event 类型性能条目。延迟响应门槛时间在 PerformanceObserver 的 observe 方法 durationThreshold 参数进行设置。

注意

在 Safari 中不支持。

var entry = {
    entryType: "first-input",
    name: "keydown",
    startTime: 1632,
    duration: 0,
    interactionId: 8048,
    processingStart: 1632.6000000238419,
    processingEnd: 1632.7000000178814,
    cancelable: true,
    target: div, 
};
var entry = {
    entryType: "event",
    name: "pointerup",
    startTime: 3648.800000011921, // 触发开始时间
    processingStart: 11052.59999999404, // 响应结束时间
    processingEnd: 20954.69999998808, // 响应开始时间
    duration: 17304, // 事件的总耗时
    cancelable: true,
    interactionId: 3520,
    target: button, // 触发事件的相关元素对象
};
// 响应延迟时间 = 响应开始时间 - 触发开始时间
const delay = entry.processingStart - entry.startTime;
// 响应处理时间 = 响应结束时间 - 响应开始时间
const processingTime = entry.processingEnd - entry.processingStart;
// 总耗时 = 响应结束时间 - 触发开始时间
const duration = entry.duration;

LayoutShift 类

条目类型为 layout-shift,包含布局偏移事件信息。

注意

在 Firefox 和 Safari 中不支持。

var entry = {
    entryType: "layout-shift",
    name: "",
    startTime: 6204.5,
    duration: 0,
    value: 0.26818976841720826, // 布局偏移分数
    hadRecentInput: true,
    lastInputTime: 6201.4000000059605,
    sources: [ // 发生偏移的元素及其位置信息
        {
            previousRect: { x: 10, y: 175, width: 676, height: 165, top: 175, right: 686, bottom: 340, left: 10 },
            currentRect: { x: 10, y: 340, width: 666, height: 63, top: 340, right: 676, bottom: 403, left: 10 },
            node: div
        },
        {
            previousRect: { x: 10, y: 340, width: 676, height: 63, top: 340, right: 686, bottom: 403, left: 10 },
            currentRect: { x: 0, y: 0, width: 0, height: 0, top: 0, right: 0, bottom: 0, left: 0 },
            node: div
        },
    ],
};

PerformanceLongTaskTiming 类

条目类型为 longtask,包含长任务事件信息。

注意

在 Firefox 和 Safari 中不支持。

var entry = {
    entryType: "longtask",
    name: "self",
    startTime: 148444.20000001788,
    duration: 1262,
    attribution: [
        {
            name: "unknown",
            entryType: "taskattribution",
            startTime: 0,
            duration: 0,
            containerType: "window",
            containerSrc: "",
            containerId: "",
            containerName: "",
        },
    ],
};

VisibilityStateEntry 类

条目类型为 visibility-state,包含页面可见性变化事件信息,其 name 分为:

  • hidden:页面隐藏
  • visible:页面显示

注意

在 Firefox 和 Safari 中不支持。

var entry = {
    entryType: "visibility-state",
    name: "hidden",
    startTime: 11006.199999988079,
    duration: 0,
};
var entry = {
    entryType: "visibility-state",
    name: "visible",
    startTime: 64040.59999999404,
    duration: 0,
};

PerformanceElementTiming 类

条目类型为 element,包含页面指定元素的渲染信息,支持 <img><p>、svg 中的 <image> 以及设置了背景的元素。

注意

在 Firefox 和 Safari 中不支持。

通过元素的 elementtiming 属性绑定监听,对应 PerformanceElementTiming 对象的 identifier 字段。

<img
    id="banner"
    elementtiming="bannerElement"
    src="https://yh.com/img/bg.9bdf4f4a.jpg"
/>
var entry = {
    name: "image-paint",
    entryType: "element",
    startTime: 346.1999999284744,
    duration: 0,
    renderTime: 0,
    loadTime: 346.1999999284744,
    intersectionRect: { x: 0, y: 0, width: 0, height: 0, top: 0, right: 0, bottom: 0, left: 0 },
    identifier: "bannerElement",
    naturalWidth: 1920,
    naturalHeight: 4100,
    id: "banner",
    url: "https://yh.com/img/bg.9bdf4f4a.jpg",
};

performance 对象

1. 对象属性

对象属性类型描述
eventCountsEventCounts返回只读的 Map 对象,包含每种事件的触发次数
timeOriginnumber返回进入页面的开始时间戳
navigation 废弃PerformanceNavigation返回当前文档的来源信息,包含 type 和 redirectCount 字段。
(请使用 PerformanceNavigationTiming 对象替代)
timing 废弃PerformanceTiming返回加载和使用当前页面期间各种事件的性能计时信息。
(请使用 PerformanceNavigationTiming 对象替代)
memory 废弃Object返回内存使用情况信息,包含字段:
jsHeapSizeLimit:最大内存
totalJSHeapSize:已分配内存
usedJSHeapSize:已使用内存
(number 类型,单位字节)
onresourcetimingbufferfullFunction设置性能条目缓存器中 resource 类型数量已满事件的回调函函数

2. 对象方法

对象方法描述
mark(name: string, options?: {detail?: string, startTime?: number}): PerformanceMark创建 PerformanceMark 对象并加入性能条目缓存器(触发 PerformanceObserver)
clearMarks(name?: string)从性能条目缓存器删除指定名称(默认所有)的 PerformanceMark 对象
measure(name: string, options?: { detail?: string, start?: number, end?: number })
measure(name: string, startMarkName: string, endMarkName: string)
创建 PerformanceMeasure 对象并加入性能条目缓存器(触发 PerformanceObserver)
clearMeasures()从性能条目缓存器删除指定名称(默认所有)的 PerformanceMeasure 对象
getEntries(): PerformanceEntryList获取性能条目缓存器中的所有对象
getEntriesByName(name: string): PerformanceEntryList根据 name 筛选性能条目缓存器中的对象
getEntriesByType(type: string): PerformanceEntryList根据 type 筛选性能条目缓存器中的对象
clearResourceTimings()清空性能条目缓存器的 resource 类型
setResourceTimingBufferSize(maxSize: number)设置性能条目缓存器中的 resource 类型最大数量(默认250)
now()开始时间(自页面加载计起的毫秒数)
toJSON()转 JSON 对象
Last Updated 2024/5/15 17:57:21