前段時間由於項目須要獲取頁面加載的時間,就去看了下HTML5中的performane。html
能夠用其得到頁面詳細的加載時間。git
關於performance的詳細內容能夠查看 http://www.cnblogs.com/CraryPrimitiveMan/p/3795086.htmlgithub
以後用performane寫了一個小工具,用來獲取頁面詳細的加載時間。chrome
GitHub上的地址是:https://github.com/CraryPrimitiveMan/performance-toolapp
只在chrome中經過了測試。dom
將times.js引入想應的HTML中,打開console(按F12),刷新一下頁面就能夠看到詳細的加載時間。 也能夠在JS中使用times()方法調用。工具
其運行結果以下圖測試
源碼及註釋以下fetch
var times = function() { var timing = performance.timing; var loadTime = timing.loadEventEnd - timing.navigationStart;//過早獲取時,loadEventEnd有時會是0 if(loadTime <= 0) { // 未加載完,延遲200ms後繼續times方法,直到成功 setTimeout(function(){ times(); }, 200); return; } var readyStart = timing.fetchStart - timing.navigationStart; var redirectTime = timing.redirectEnd - timing.redirectStart; var appcacheTime = timing.domainLookupStart - timing.fetchStart; var unloadEventTime = timing.unloadEventEnd - timing.unloadEventStart; var lookupDomainTime = timing.domainLookupEnd - timing.domainLookupStart; var connectTime = timing.connectEnd - timing.connectStart; var requestTime = timing.responseEnd - timing.requestStart; var initDomTreeTime = timing.domInteractive - timing.responseEnd; var domReadyTime = timing.domComplete - timing.domInteractive; //過早獲取時,domComplete有時會是0 var loadEventTime = timing.loadEventEnd - timing.loadEventStart; // 爲console.table方法準備對象,包含耗時的描述和消耗的時間 var allTimes = [ { "描述": "準備新頁面時間耗時", "時間(ms)": readyStart }, { "描述": "redirect 重定向耗時", "時間(ms)": redirectTime }, { "描述": "Appcache 耗時", "時間(ms)": appcacheTime }, { "描述": "unload 前文檔耗時", "時間(ms)": unloadEventTime }, { "描述": "DNS 查詢耗時", "時間(ms)": lookupDomainTime }, { "描述": "TCP鏈接耗時", "時間(ms)": connectTime }, { "描述": "request請求耗時", "時間(ms)": requestTime }, { "描述": "請求完畢至DOM加載", "時間(ms)": initDomTreeTime }, { "描述": "解釋dom樹耗時", "時間(ms)": domReadyTime }, { "描述": "load事件耗時", "時間(ms)": loadEventTime }, { "描述": "從開始至load總耗時", "時間(ms)": loadTime } ]; console.table(allTimes); } window.onload = times;// onload時,觸發times方法