近期,接到需求需要對前端性能做一個監控,數據做一個上報。基于此,開始了采坑之旅。
首先,我們理解一個前端常見問題,一個網頁從打開到顯示經歷了什么?
頁面過程.png
我們只是將url輸入到瀏覽器居然就經歷了這么多過程,每一個過程都可以寫很多,不是這期的重點,這期的重點是監控前端的性能,簡單點說就是監控這些花費的時間。
最主要的是首屏時間和總的時間,首屏時間的長短決定了用戶的留存。
開搞,查了很多資料,一般有兩種方法,一種是通過寫個函數計時;另一種是webapi Performance.timing 來獲取。
這次選擇了Performance.timing;其實兩種方法獲取到的時間都不是精確時間,所以怎么方便怎么來咯。
注意,Performance.timing是較新的api,使用ie瀏覽器的話低于ie9就不支持了。
Performance.timing能獲取很多時間節點,
查文檔,文檔里有較為清楚的圖解
timing-overview.png
- navigationStart
- redirectStart
- unloadEventStart
- unloadEventEnd
- redirectEnd
- fetchStart
- domainLookupStart
- domainLookupEnd
- connectStart
- (secureConnectionStart)
- connectEnd
- requestStart
- responseStart
- responseEnd
- domLoading
- domInteractive
- domContentLoadedEventStart
- domContentLoadedEventEnd
- domComplete
- loadEventStart
- loadEventEnd
通過時間節點可以大致算出
- DNS查詢耗時 :domainLookupEnd - domainLookupStart
- TCP鏈接耗時 :connectEnd - connectStart
- request請求耗時 :responseEnd - responseStart
- 解析dom樹耗時 : domComplete- domInteractive
- 白屏時間 :responseStart - navigationStart
- domready時間 :domContentLoadedEventEnd - navigationStart
- onload時間 :loadEventEnd - navigationStart
搞定收工,在實際開發中,出現了大坑,計算onload時間的時候loadEventEnd為0,打出log發現不是,相減的時候就是0了,可能是由于使用的是appwebview提前加載的緣故,只能將Performance.timing傳給app計算了,計算正常。