performance解讀頁面性能 (chrome)

// 計算程序執行的精確時間
function getFunctionTimeWithDate (func) {  
    var timeStart = Date.now();
 
    // 執行開始
    func();
    // 執行結束
    var timeEnd = Date.now();
 
    // 返回執行時間
    return (timeEnd - timeStart);
}
function getPerformanceTiming () {  
    var performance = window.performance;
 
    if (!performance) {
        // 當前瀏覽器不支持
        console.log('你的瀏覽器不支持 performance 接口');
        return;
    }
 
    var t = performance.timing;
    var times = {};
 
    //【重要】頁面加載完成的時間
    //【緣由】這幾乎表明了用戶等待頁面可用的時間
    times.loadPage = t.loadEventEnd - t.navigationStart;
 
    //【重要】解析 DOM 樹結構的時間
    //【緣由】檢討下你的 DOM 樹嵌套是否是太多了!
    times.domReady = t.domComplete - t.responseEnd;
 
    //【重要】重定向的時間
    //【緣由】拒絕重定向!好比,http://example.com/ 就不應寫成 http://example.com
    times.redirect = t.redirectEnd - t.redirectStart;
 
    //【重要】DNS 查詢時間
    //【緣由】DNS 預加載作了麼?頁面內是否是使用了太多不一樣的域名致使域名查詢的時間太長?
    // 可以使用 HTML5 Prefetch 預查詢 DNS ,見:[HTML5 prefetch](http://segmentfault.com/a/1190000000633364)            
    times.lookupDomain = t.domainLookupEnd - t.domainLookupStart;
 
    //【重要】讀取頁面第一個字節的時間
    //【緣由】這能夠理解爲用戶拿到你的資源佔用的時間,加異地機房了麼,加CDN 處理了麼?加帶寬了麼?加 CPU 運算速度了麼?
    // TTFB 即 Time To First Byte 的意思
    // 維基百科:https://en.wikipedia.org/wiki/Time_To_First_Byte
    times.ttfb = t.responseStart - t.navigationStart;
 
    //【重要】內容加載完成的時間
    //【緣由】頁面內容通過 gzip 壓縮了麼,靜態資源 css/js 等壓縮了麼?
    times.request = t.responseEnd - t.requestStart;
 
    //【重要】執行 onload 回調函數的時間
    //【緣由】是否太多沒必要要的操做都放到 onload 回調函數裏執行了,考慮過延遲加載、按需加載的策略麼?
    times.loadEvent = t.loadEventEnd - t.loadEventStart;
 
    // DNS 緩存時間
    times.appcache = t.domainLookupStart - t.fetchStart;
 
    // 卸載頁面的時間
    times.unloadEvent = t.unloadEventEnd - t.unloadEventStart;
 
    // TCP 創建鏈接完成握手的時間
    times.connect = t.connectEnd - t.connectStart;
 
    return times;
}
console.log(getFunctionTimeWithDate(getPerformanceTiming));css

相關文章
相關標籤/搜索