前端性能監控之performance API

前端開發完之後,業務說太卡,你優化吧。我打開一個離職的同事的代碼,複用到是用的挺好的,不過把一個城市級聯裡面下載數據的環節封裝到組件中,頁面中有8個地方都用到了,打開網絡請求,真的就下載了8次2M的城市數據。幸好我們網絡情況還不錯,也就每次頁面打開前卡半分鐘而已,呵呵了。

在前後端分離的大環境下,前端優化也越來越重要。無論從視覺、性能、頁面邏輯上進行優化,都可以比較直觀的提升用戶體驗。當然,優化的前提是知道我哪裡慢了,performance API就是進行這樣的監控的。

性能監控

直接在控制打印performance就可以得到所有性能監測的信息了,裡面包含幾個部分。

  • memory(Chrome中內存)
jsHeapSizeLimit: 內存大小限制
totalJSHeapSize: 可使用內存
usedJSHeapSize: 已使用內存
  • navigation(上下文網頁導航)
  • onresourcetimingbufferfull(資源時間性能緩衝區事件鉤子)
  • timeOrigin(基準時間)
  • timing(節點時間)


通過拆解計算各個節點時間的間隔就是每個環節的使用情況了。

下面放一個頁面函數顯示當前頁面的各階段加載的時間顯示。

function performanceTest() {
let timing = performance.timing,
readyStart = timing.fetchStart - timing.navigationStart,
redirectTime = timing.redirectEnd - timing.redirectStart,
appcacheTime = timing.domainLookupStart - timing.fetchStart,
unloadEventTime = timing.unloadEventEnd - timing.unloadEventStart,
lookupDomainTime = timing.domainLookupEnd - timing.domainLookupStart,
connectTime = timing.connectEnd - timing.connectStart,
whiteScreenTime = timing.responseStart - timing.navigationStart,
requestTime = timing.responseEnd - timing.requestStart,
initDomTreeTime = timing.domInteractive - timing.responseEnd,
domReadyTime = timing.domComplete - timing.domInteractive,
loadEventTime = timing.loadEventEnd - timing.loadEventStart,
loadTime = timing.loadEventEnd - timing.navigationStart;
console.log('準備新頁面時間耗時: ' + readyStart);
console.log('redirect 重定向耗時: ' + redirectTime);
console.log('Appcache 耗時: ' + appcacheTime);
console.log('unload 前文檔耗時: ' + unloadEventTime);
console.log('DNS 查詢耗時: ' + lookupDomainTime);
console.log('TCP連接耗時: ' + connectTime);
console.log('白屏時間: ' + whiteScreenTime);
console.log('request請求耗時: ' + requestTime);
console.log('請求完畢至DOM加載: ' + initDomTreeTime);
console.log('解析DOM樹耗時: ' + domReadyTime);
console.log('load事件耗時: ' + loadEventTime);
console.log('加載時間耗時: ' + loadTime);
}


performance 方法

  1. clearMarks() 清理打點標記
  2. clearMeasures() 清理連線標記
  3. clearResourceTimings() 重置緩衝區域大小
  4. getEntries() 獲取所有資源分節點加載時間
  5. getEntriesByName() 通過Name獲取所有資源分節點加載時間
  6. getEntriesByType() 通過Type獲取所有資源分節點加載時間
  7. mark() 增加打點標記
  8. measure() 增加打點連線標記
  9. now() 從獲取基準時間到當前時間的間隔,精確到微秒百萬分之一秒,呃
  10. setResourceTimingBufferSize() 設置緩衝區域大小


數據埋點

埋點中除了業務相關之外的性能埋點,可以自行編輯,也可以通過上面的相關API進行更加精確的時間計算。


chrome開發這工具的Performance面板

本地開發調試的話,chrome中提供了關於Performance情況更加詳細的報表數據,精確到每個資源,每個時間點頁面的渲染效果,後續就可以針對環節進行專項優化(像我這種密集恐懼的人,看的還有點慌呢)

前端性能監控之performance API


使用上的性能面板的時候,如果你的chrome上安裝了很多插件的話,建議打開無痕模式進行調試。


文末

關於performanceAPI是建立在chrome瀏覽器的基礎上使用的,其他瀏覽器兼容情況暫時沒有去深究。

前端優化,從網絡開始請求,到最後渲染結束,中間方方面面的環節,都可以進行很多優化,前端優化雅虎軍規依然是優化方向,每一個環節都可以寫出來很多文章。

前端性能監控之performance API



分享到:


相關文章: