介紹利用H5 api接口performance,統計網站的加載時間,進而優化加載速度。
在做H5項目的時候,首屏加載會是一個比較重要的部分,加載越快,用戶流失就會越少,受限于網絡等原因,可能一些人看到首頁較快,一些人看到首頁較慢,然后作為程序員卻無法準確得知加載慢是因為什么原因造成的,沒有辦法去細化優化點。
幸運的是H5新API接口performance能讓我們做的更多一點
window.onload = function(){
setTimeout(function(){
with(performance){
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.domContentLoadedEventEnd - timing.navigationStart;
loadTime = timing.loadEventEnd - timing.navigationStart;
//過早獲取時 domComplete有時會是0loadEventTime = 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總耗時: ' + loadTime);
}
},2000)
}
通過分析,發現用此方法 DOM加載完成和全部加載完成耗用的時間和chrome瀏覽器NETWORDK面板上顯示的DomContentLoaded 、Load時間基本一致,誤差幾ms,
所以我們基本上可以用這個方法來統計我們所做的H5網站在不同地域、不同客戶端下加載H5所耗用的時間,進而逐個優化。比如DNS耗時拉 DOM加載耗時了 等等
window.performance.timing.jpg