主流指标
- FP(First Paint): 首次绘制,指页面开始显示内容的时间点。
- FCP(First Contentful Paint): 首次内容绘制,指页面上第一个文本或图像等内容绘制的时间点。
- TTI(Time to Interactive): 可交互时间,指页面元素可以稳定、响应用户操作的时间点。
- LCP(Largest Contentful Paint): 最大内容绘制,指在视口中最大的页面内容元素绘制的时间点。
- CLS(Cumulative Layout Shift): 累积布局偏移,衡量视觉稳定性,指页面在加载过程中元素移位的程度。
- child::首屏加载速度
收集监测并上传结果
要在前端实现性能监控,以下为几个关键步骤:
自动化性能数据收集
可以使用Performance API来自动化地收集性能数据。例如,使用 window.performance 来监控各种性能指标。
if ('performance' in window) {
window.addEventListener('load', function() {
const perfData = window.performance.timing;
const pageLoadTime = perfData.loadEventEnd - perfData.navigationStart;
const domReadyTime = perfData.domContentLoadedEventEnd - perfData.navigationStart;
// 其他需要监控的性能指标...
});
}对于新的性能指标,可以使用Performance Observer API来监控:
if ('PerformanceObserver' in window) {
let perfObserver = new PerformanceObserver((list) => {
let entries = list.getEntries();
for (let entry of entries) {
// 处理每个性能指标项...
}
});
perfObserver.observe({ entryTypes: ['paint', 'layout-shift', 'longtask'] });
}监控用户的真实体验
使用Navigation Timing API和Resource Timing API等,可以帮助我们收集到实际用户在页面上的加载时间、资源加载时间等。
// 使用Navigation Timing API获取更多加载时间数据
const navTiming = performance.getEntriesByType('navigation')[0];
console.log('Time to Interactive (TTI):', navTiming.interactive);
console.log('Largest Contentful Paint (LCP):', navTiming.largestContentfulPaint);
// 获取CLS值
const clsValue = getCLS();
console.log('Cumulative Layout Shift:', clsValue);
// 获取资源加载时间
const resourceTimings = performance.getEntriesByType('resource');
resourceTimings.forEach((resource) => {
console.log(`Time taken to load ${resource.name}:`, resource.responseEnd - resource.startTime);
});数据上报与分析
在收集完性能数据后,需要将这些数据上报到服务器进行处理和长期存储。这一步通常通过Ajax或者Navigator.sendBeacon API来异步发送数据。
function reportPerformanceData(data) {
if (navigator.sendBeacon) {
navigator.sendBeacon('/report-performance', JSON.stringify(data));
} else {
// 备用方案:使用Ajax来发送数据
let xhr = new XMLHttpRequest();
xhr.open('POST', '/report-performance', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
}
}业务绩效与性能指标结合
除了通用性能指标,我们也应关注与业务相关的特定绩效指标。例如,电商网站可能需要关注商品图像的加载速度,社交网站可能关心首条信息的展现时间等。
// 监控特定元素的加载时间
let imgEl = document.getElementById('product-img');
if (imgEl) {
imgEl.onload = function() {
let loadTime = Date.now() - performance.timing.navigationStart;
console.log('Time taken to load product image:', loadTime);
reportPerformanceData({ 'productImageLoadTime': loadTime });
};
}