瀏覽器新提供的performance接口精確的告訴我們當訪問一個網站頁面時當前網頁每個處理階段的精確時間(timestamp),以方便我們進行前端分析。
它是瀏覽器的直接實現,比之前在網頁中用js設置Date.time或者cookie來分析網頁時間上要精確很多。
以下是w3c提供的performance.timing各階段api圖
暫時的缺點:
Navigation Timing stops at the window.onload event
現代的網站很多是在onload之后再發觸發更多的異步請求,而navigation Timing統計卻只在window.onload之后就不統計了 。
為什么不在所有的網絡請求完成后統計timing呢?
因為要考慮到有些網頁有輪詢或者長鏈接的情況。所以情況就復雜了,w3c還在草案階段。如果你夠牛想出好的解決方案,也可以直接發郵件到w3c去,貢獻你的一份力量。
為方便查看統計值,自己寫了一個簡單的統計表插件
performance API 耗時統計
統計點:
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; requestTime = timing.responseEnd - timing.requestStart; initDomTreeTime = timing.domInteractive - timing.responseEnd; domReadyTime = timing.domComplete - timing.domInteractive; //過早獲取時 domComplete有時會是0 loadEventTime = timing.loadEventEnd - timing.loadEventStart; loadTime = timing.loadEventEnd - timing.navigationStart;//過早獲取時 loadEventEnd有時會是0
結果:
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('request請求耗時: ' + requestTime); console.log('請求完畢至DOM加載: ' + initDomTreeTime); console.log('解釋dom樹耗時: ' + domReadyTime); console.log('load事件耗時: ' + loadEventTime); console.log('從開始至load總耗時: ' + loadTime);
使用方法:
可以直接在html底部引入performance-min.js
或下載chrome 插件.crx包,
注意事項
由於window.performance.timing還處於w3c完善過程中,當你的網站有異步請求時,請在所有異步請求完成后再點擊chrome上的插件按鈕,以確保數據正確
效果圖:
=======================================================================
js及chrome插件下載地址
github: https://github.com/willian12345/performanceTracer
關於performance timing 未完善功能老外的討論:http://www.stevesouders.com/blog/2012/10/30/qa-nav-timing-and-post-onload-requests/
==========================
bug修復 :
現chrome下可以安裝插件了,mac與win下已測試,其它系統上應該也可以安裝使用了。
==========================
轉載處請注明:博客園偷飯貓willian12345@126.com