// 白屏时间
// Vite环境下Vue项目的main.js或入口文件中引入这段代码
if ("performance" in window) {
const perf = performance;
let fpTime;
if (perf.getEntriesByName) {
const entry = perf.getEntriesByName("first-paint")[0];
if (entry) {
fpTime = entry.startTime;
}
} else if (window.performance.timing) {
// 对不支持Performance Paint Timing API的老版本浏览器,可以尝试使用navigationStart和firstPaint
fpTime = perf.timing.firstPaintTime;
// 若老版浏览器也不支持,则可考虑自定义测量方式,如设置pageStartTime
}
if (fpTime) {
// fpTime即为白屏时间,需要转换为相对时间戳(相对于navigationStart)
const whiteScreenTime = fpTime - perf.timing.navigationStart;
console.log("白屏时间: ", whiteScreenTime.toFixed(2), "ms");
}
}
// 首屏加载时间
// 计算First Contentful Paint (FCP)
let fcpTime;
if (perf.getEntriesByName) {
const entry = perf.getEntriesByName("first-contentful-paint")[0];
if (entry) {
fcpTime = entry.startTime;
}
}
if (fcpTime) {
const firstScreenTime = fcpTime - perf.timing.navigationStart;
console.log("首屏时间: ", firstScreenTime.toFixed(2), "ms");
}
用在main.js文件中