performace的兼容寫法
var t = new Object(); var performance = window.performance || window.msPerformance || window.webkitPerformance; var resource = performance.getEntriesByType('resource') if ( resource && resource[0] ) { t = resource[0]; } else if (performance && performance.timing) { t = performance.timing; }
1、DNS查詢耗時
t.domainLookupEnd - t.domainLookupStart || 0;
PerformaceTiming.domainLookupStart為域名開始解析時的 Unix毫秒時間戳
PerformaceTiming.domainLookupEnd為解析域名結束時的 Unix毫秒時間戳,
2、TCP建立連接耗時
t.connectEnd - t.connectStart;
PerformaceTiming.connectStart HTTP請求開始向服務器發送時的Unix毫秒時間戳
PerformaceTiming.connected瀏覽器與服務器之間的連接建立時的Unix毫秒時間戳
3、TTFB收到第一字節耗時
t.responseStart - t.requestStart;
PerformaceTiming.responseStart瀏覽器從服務器收到(或從本地緩存讀取)第一個字節時的Unix毫秒時間戳
PerformaceTiming.requestStart瀏覽器向服務器發出HTTP請求時(或開始讀取本地緩存時)的Unix毫秒時間戳。
4、Trans文本傳輸耗時
t.responseEnd - t.responseStart
PerformaceTiming.responseEnd瀏覽器從服務器收到(或從本地緩存讀取,或從本地資源讀取)最后一個字節時(如果在此之前HTTP連接已經關閉,則返回關閉時)的Unix毫秒時間戳。
5、Dom DOM結構解析耗時
body完成,header中寫的js(不含defer屬性)會影響該值.
t.domInteractive - t.responseEnd;
PerformaceTiming.domInteractive當前網頁DOM結構結束解析、開始加載內嵌資源時(即Document.readyState
屬性變為“interactive”、相應的readystatechange
事件觸發時)的Unix毫秒時間戳。
PerformaceTiming.responseEnd瀏覽器從服務器收到(或從本地緩存讀取,或從本地資源讀取)最后一個字節時(如果在此之前HTTP連接已經關閉,則返回關閉時)的Unix毫秒時間戳。
6、SSL安全鏈接耗時
t.connectEnd - t.secureConnectionStart;
PerformaceTiming.
connected瀏覽器與服務器之間的連接建立時的Unix毫秒時間戳
PerformaceTiming.secureConnectionStart瀏覽器與服務器開始安全鏈接的握手時的Unix毫秒時間戳
7、FP首次繪制
if (performance && performance.getEntries) { var perfEntries = performance.getEntries(); for (var key in perfEntries) { if ( perfEntries[key].name && perfEntries[key].name === 'first-contentful-paint' && perfEntries[key].startTime ) { var fcp = perfEntries[key].startTime.toFixed(0) * 1; } if ( perfEntries[key].name && perfEntries[key].name === 'first-paint' && perfEntries[key].startTime ) { var fp = perfEntries[key].startTime.toFixed(0) * 1; } } }
8、FCP首次內容繪制
perfEntries[key].startTime.toFixed(0) * 1;
9、重定向耗時
if (t.navigationStart !== undefined) { rd = t.fetchStart - t.navigationStart } else if (t.redirectEnd !== undefined) { rd = t.redirectEnd - t.redirectStart } else { rd = 0 }
10、FMP有意義的繪畫時間
https://github.com/iyjhabc/first-meaningful-paint/blob/master/src/index.js
11、TTI html加載耗時
t.domInteractive - t.fetchStart;
PerformaceTiming.fetchStart,表征了瀏覽器准備好使用HTTP請求來獲取(fetch)文檔的UNIX時間戳。這個時間點會在檢查任何應用緩存之前。
12、Ready domContentLoaded耗時
t.domContentLoadedEventEnd - t.fetchStart
13、onload 加載完成耗時
t.loadEventStart - t.fetchStart;
參考: https://developer.mozilla.org/zh-CN/docs/Web/API/PerformanceTiming