window.addEventListener('load', (event) => {
// Time to Interactive 可交互时间
let timing = performance.getEntriesByType('navigation')[0];
console.log(timing.domInteractive);
console.log(timing.fetchStart);
let diff = timing.domInteractive - timing.fetchStart;
console.log("TTI: " + diff);
})
观察长任务
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log(entry)
}
})
observer.observe({entryTypes: ['longtask']})
页面可见性的状态监听
let vEvent = 'visibilitychange';
if (document.webkitHidden != undefined) {
// webkit 事件名称
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);
用户网络状态监听
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);
常用性能指标计算
domainLookupEnd - domainLookupStart
connectEnd - connectStart
connectEnd - secureConnectionStart
responseStart - requestStart
responseEnd - responseStart
domInteractive - responseEnd
loadEventStart - domContentLoadedEventEnd
responseStart - domainLookupStart
responseEnd - fetchStart
domInteractive - fetchStart
domContentLoadEventEnd - fetchStart
loadEventStart - fetchStart
transferSize - encodedBodySize
performance.navigation.redirectCount
redirectEnd - redirectStart
性能APIs实例