大家好,我是Sunshine,今天给大家介绍一个非常好用的浏览器api:PerformanceObserver,我们可以用它来获取首屏、白屏时间,您不必费心手动计算它。1.简介PerformanceObserver可以用来获取性能相关的数据,比如首帧fp、首屏fcp、首有意义绘图fmp等。构造函数PerformanceObserver()创建并返回一个新的PerformanceObserver对象。提供的方法PerformanceObserver.observe()会在记录的性能指标在指定的entryTypes中时调用性能观察器的回调函数。PerformanceObserver.disconnect()停止性能观察器回调以接收性能指标。PerformanceObserver.takeRecords()返回存储在性能观察器中的性能指标列表并将其清除。我们看一下observer.observe(options)options,一个只包含单个键值对的对象,键值对的键名指定为entryTypes。entryTypes的取值要求如下:entryTypes的取值:字符串数组,字符串的有效值在PerformanceEntryTypes中有详细列出。如果其中一个字符串取了无效值,浏览器会自动忽略它。注意:如果没有传入options参数,或者传入的options参数为空数组,将抛出TypeError。2.示例获取结果根据打印结果我们可以推断entryTypes中的值其实就是我们告诉PerformanceObserver我们想要获取的某一方面的性能值。比如传入paint就是我们要获取fcp和fp。所以我们查看print,它会打印fp和fcp。这里有必要解释一下什么是fp、fcp、fpmTTFB:TimeToFirstByte,firstbyte时间FP:FirstPaint,firstdrawing,drawingBodyFCP:FirstContentfulPaint,firstdrawingwithcontent,firstdomelementdrawingcompletedFMP:FirstMeaningfulPaint,第一个有意义的绘图TTI:TimeToInteractive,交互时间,整个内容都被渲染了不懂?看图片!FP只有一个div根节点FCP包含页面的基本框架,但没有数据内容FMP包含页面的所有元素和数据哇!恍然大悟!3、实际使用后,我们在实际项目中如何获取?你可以看看我的实现以供参考://使用PerformanceObserver监控fcpif(!!PerformanceObserver){try{consttype='paint';if((PerformanceObserver.supportedEntryTypes||[]).includes(type)){observer=newPerformanceObserver((entryList)=>{for(constentryofentryList.getEntriesByName('first-contentful-paint')){const{startTime,duration}=entry;console.log('[assets-load-monitor]PerformanceObserverfcp:',startTime+duration);//报告startTime操作}});观察者。observe({entryTypes:[类型],});返回;}}catch(e){//ios不支持这个entryTypes,会报错https://caniuse.com/?search=PerformancePaintTimingconsole.warn('[assets-load-monitor]PerformanceObserver错误:',(e||{}).message?e.message:e);这里使用的是为了判断是否可以使用PerformanceObserver,如果不能,我们使用其他方法,比如MutationObserver,这个后面会讲到4.参考文章:https://blog.csdn.net/weixin_40970987/article/details/108121988https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver/observe。
