性能測量

// 計(jì)算一些關(guān)鍵的性能指標(biāo)
window.addEventListener('load', (event) => {
    // Time to Interactive
    const timing = performance.getEntriesByType('navigation')[0];
    console.log(timing.domInteractive);
    console.log(timing.fetchStart);
    const diff = timing.domInteractive - timing.fetchStart;
    console.log("TTI: " + diff);
})
// 觀察長任務(wù)
const observer = new PerformanceObserver((list) => {
    for (const entry of list.getEntries()) {
        console.log(entry)
    }
})

observer.observe({entryTypes: ['longtask']})
// 界面可見性的狀態(tài)監(jiān)聽
let vEvent = 'visibilitychange';
if (document.webkitHidden != undefined) {
    // webkit prefix detected
    vEvent = 'webkitvisibilitychange';
}

function visibilityChanged() {
    if (document.hidden || document.webkitHidden) {
        console.log("Web page is hidden.")
    } else {
        console.log("Web page is visible.")
    }
}

document.addEventListener(vEvent, visibilityChanged, false);
// 網(wǎng)絡(luò)狀態(tài)監(jiān)聽
const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
let type = connection.effectiveType;

function updateConnectionStatus() {
  console.log("Connection type changed from " + type + " to " + connection.effectiveType);
  type = connection.effectiveType;
}

connection.addEventListener('change', updateConnectionStatus);
const {performance, PerformanceObserver} = require('perf_hooks');

const add = (a, b) => a+b;

const num1 = 1;
const num2 = 2;

performance.mark('start');

for(let i = 0; i < 10000000; i++) {
  add(num1, num2);
}

add(num1, 's');

for(let i = 0; i < 10000000; i++) {
  add(num1, num2);
}

performance.mark('end');

const observer = new PerformanceObserver((list) => {
  console.log(list.getEntries()[0]);
})
observer.observe({entryTypes: ['measure']});

performance.measure('測量1', 'start', 'end');

其他耗時(shí)計(jì)算公式:

DNS 解析耗時(shí): domainLookupEnd - domainLookupStart
TCP 連接耗時(shí): connectEnd - connectStart
SSL 安全連接耗時(shí): connectEnd - secureConnectionStart
網(wǎng)絡(luò)請求耗時(shí) (TTFB): responseStart - requestStart
數(shù)據(jù)傳輸耗時(shí): responseEnd - responseStart
DOM 解析耗時(shí): domInteractive - responseEnd
資源加載耗時(shí): loadEventStart - domContentLoadedEventEnd
First Byte時(shí)間: responseStart - domainLookupStart
白屏?xí)r間: responseEnd - fetchStart
首次可交互時(shí)間: domInteractive - fetchStart
DOM Ready 時(shí)間: domContentLoadEventEnd - fetchStart
頁面完全加載時(shí)間: loadEventStart - fetchStart
http 頭部大?。?transferSize - encodedBodySize
重定向次數(shù):performance.navigation.redirectCount
重定向耗時(shí): redirectEnd - redirectStart
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容