前端工程性能优化系列(一)

410 阅读1分钟

PerformanceObserver可以用于获取首帧fp,首屏scp,首次有意义的绘制fmp等等;

1,先看看MDN上有怎样的解释:

PerformanceObserver() 构造函数使用给定的观察者 callback 生成一个新的 PerformanceObserver 对象。当通过 observe() 方法注册的 条目类型 的 性能条目事件 被记录下来时,调用该观察者回调.

语法

`var observer = new PerformanceObserver(callback);`

参数

callback

观察的性能事件被记录时将调用 PerformanceObserverCallback 回调。调用回调时,其第一个参数是 性能观察条目列表 (en-US),第二个参数是 观察者 对象;

先看看有什么api:

var observer = new PerformanceObserver(function(list, obj) {

var entries = list.getEntries();

for (let entry of entries) {

   // Process "mark" and "frame" events

   console.groupCollapsed(entry.name)

   console.log(entry.entryType)

   console.log(entry.startTime)

   console.log(entry.duration)

   console.groupEnd(entry.name)

}

});

observer.observe({entryTypes: ["longtask", 'frame', 'navigation', 'resource', 'mark', 'measure','paint']});

// longtask: 即检测项目中是否有长运行的任务

// paint: 返回我们想要的FCP 和 FP

2, 实际使用:

// 使用performanceObserve 监听FCP

if (!!PerformanceObserver) {

try {

const type = 'paint';

if ((PerformanceObserver.supportedEntryTypes || []).includes(type)) {

   let observer = new PerformanceObserver((entryList) => {

   for (const entry of entryList.getEntriesByName('first-contentful-paint')) {

     const { startTime, duration } = entry;

     console.log('FCP: ', startTime + duration);

   }

  });

observer.observe({

   entryTypes: [type]

});

return;

}

} catch (error) {

// ios 不支持这种entryTypes, 会导致报错

   console.error(error);

}

}

3, 更多例子:

// import { performance } from 'util';

const performance = window.performance;

console.log(performance); // 打印看看有什么

const add = (a, b) => a+b;

let num1 = 1, num2 = 2;

performance.mark('start');

for (let index = 0; index < 1000000; index++) {

   add(num1, num2);

}

add(num1, 's');

for (let index = 0; index < 1000000; index++) {

   add(num1, num2);

}

performance.mark('end');

var observer = new PerformanceObserver(function(list) {

var entry = list.getEntries()[0];

   console.log(entry);

});

observer.observe({entryTypes: ["measure"]});

performance.measure('测量1', 'start', 'end'); // 告诉它测量开始和结束的位置

结果:

4, 获取页面中的长运行任务(长耗时,比如频繁操作dom的):

// 性能测量

this.performance = window.performance;

// 测量开始

this.performance.mark('start-test');

const observer = new PerformanceObserver((list) => {

for (const entry of list.getEntries()) {

// 打印

console.log(entry);

}

});

// 你想测量的函数或耗时的操作

await api.getList();

// // 测量结束

this.performance.mark('end-test');

observer.observe({entryTypes: ['longtask']});

结果: