PerformanceObserver自動獲取首屏時間實現示例
介紹
PerformanceObserver 可用于獲取性能相關的數據,例如首幀fp、首屏fcp、首次有意義的繪制 fmp等等。
構造函數
PerformanceObserver()
創建并返回一個新的 PerformanceObserver 對象。
提供的方法
PerformanceObserver.observe()
當記錄的性能指標在指定的 entryTypes 之中時,將調用性能觀察器的回調函數。
PerformanceObserver.disconnect()
停止性能觀察者回調接收到性能指標。
PerformanceObserver.takeRecords()
返回存儲在性能觀察器中的性能指標的列表,并將其清空。
重點我們看看observer.observe(options);
options
一個只裝了單個鍵值對的對象,該鍵值對的鍵名規定為 entryTypes。entryTypes 的取值要求如下:
entryTypes 的值:一個放字符串的數組,字符串的有效值取值在性能條目類型 中有詳細列出。如果其中的某個字符串取的值無效,瀏覽器會自動忽略它。
另:若未傳入 options 實參,或傳入的 options 實參為空數組,會拋出 TypeError。
實例
<script> const observer = new PerformanceObserver((list) => { for(const entry of list.getEntries()){ 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']}); </script>
獲取結果
根據打印結果我們可以推測出來:
entryTypes里的值其實就是我們告訴PerformanceObserver,我們想要獲取的某一方面的性能值。例如傳入paint,就是說我們想要得到fcp和fp。
所以我們看打印,它打印出來了fp和fcp
這里有必要解釋一下什么是fp,fcp,fpm
TTFB:Time To First Byte,首字節時間
FP:First Paint,首次繪制,繪制Body
FCP:First Contentful Paint,首次有內容的繪制,第一個dom元素繪制完成
FMP:First Meaningful Paint,首次有意義的繪制
TTI:Time To Interactive,可交互時間,整個內容渲染完成
不懂?看圖!
FP僅有一個div根節點
FCP包含頁面的基本框架,但沒有數據內容
FMP包含頁面的所有元素及數據
Wow!恍然大悟!
實際使用
好了,我們在實際項目中怎么取獲取呢?可以看看我的實現參考一下下:
// 使用 PerformanceObserver 監聽 fcp if (!!PerformanceObserver){ try { const type = 'paint'; if ((PerformanceObserver.supportedEntryTypes || []).includes(type)) { observer = new PerformanceObserver((entryList)=>{ for(const entry of entryList.getEntriesByName('first-contentful-paint')){ const { startTime } = entry; console.log('[assets-load-monitor] PerformanceObserver fcp:', startTime); // 上報startTime操作 } }); observer.observe({ entryTypes: [type], }); return; } } catch (e) { // ios 不支持這種entryTypes,會報錯 https://caniuse.com/?search=PerformancePaintTiming console.warn('[assets-load-monitor] PerformanceObserver error:', (e || {}).message ? e.message : e); } }
這里用了判斷是否可以使用PerformanceObserver,不能使用的話,我們是用其他方法的,例如MutationObserver,這個我們我們后面再講。
參考:
https://developer.mozilla.org/zh-CN/docs/Web/API/PerformanceObserver/observe
http://www.gpbgw.com/article/95836.htm
以上就是PerformanceObserver獲取首屏時間實現示例的詳細內容,更多關于PerformanceObserver首屏時間的資料請關注腳本之家其它相關文章!
相關文章
微信小程序 加載 app-service.js 錯誤解決方法
這篇文章主要介紹了微信小程序 加載 app-service.js 錯誤詳解的相關資料,在開發微信小程序過程中出現了app-services.js的錯誤,并解決此問題,需要的朋友可以參考下2016-10-10
最新評論