Appearance
性能监控
performance.timing这个api已经被慢慢废弃了。
performance.timing与performance.getEntriesByType('navigation')[0]两个时间统计会有点差异,前者是绝对时间,后者统计的时间都是相对本次请求开始作为起始时间,这点比较重要。
js
window.addEventListener('load', function() {
const [performanceData] = performance.getEntriesByType("navigation");
})window.addEventListener('load', function() {
const [performanceData] = performance.getEntriesByType("navigation");
})计算页面加载时间
js
performanceData.loadEventEnd - performanceData.domCompleteperformanceData.loadEventEnd - performanceData.domComplete计算请求响应时间
js
performanceData.responseEnd - performanceData.requestStartperformanceData.responseEnd - performanceData.requestStart计算DNS查询时间
js
performanceData.domainLookupEnd - performanceData.domainLookupStartperformanceData.domainLookupEnd - performanceData.domainLookupStart计算TCP连接时间
js
performanceData.connectEnd - performanceData.connectStart;performanceData.connectEnd - performanceData.connectStart;计算白屏时间
js
performanceData.domInteractive - performanceData.responseStartperformanceData.domInteractive - performanceData.responseStart计算FCP
js
let fcpTime = 0;
const [fcpEntry] = performance.getEntriesByName("first-contentful-paint");
if (fcpEntry) {
fcpTime = fcpEntry.startTime;
}let fcpTime = 0;
const [fcpEntry] = performance.getEntriesByName("first-contentful-paint");
if (fcpEntry) {
fcpTime = fcpEntry.startTime;
}计算LCP
js
let lcpTime = 0;
const lcpEntries = performance.getEntriesByType("largest-contentful-paint");
if (lcpEntries.length > 0) {
lcpTime = lcpEntries[lcpEntries.length - 1].renderTime || lcpEntries[lcpEntries.length - 1].loadTime;
}let lcpTime = 0;
const lcpEntries = performance.getEntriesByType("largest-contentful-paint");
if (lcpEntries.length > 0) {
lcpTime = lcpEntries[lcpEntries.length - 1].renderTime || lcpEntries[lcpEntries.length - 1].loadTime;
}计算 TBT、TTI
js
// 监听长任务
let tti = 0;
let tbt = 0;
const observer = new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
// 计算 TBT
if (entry.duration > 50) {
tbt += entry.duration - 50;
}
}
// 计算 TTI
if (tti === 0 && tbt < 50) {
tti = performance.now();
}
});
observer.observe({ entryTypes: ["longtask"] });// 监听长任务
let tti = 0;
let tbt = 0;
const observer = new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
// 计算 TBT
if (entry.duration > 50) {
tbt += entry.duration - 50;
}
}
// 计算 TTI
if (tti === 0 && tbt < 50) {
tti = performance.now();
}
});
observer.observe({ entryTypes: ["longtask"] });