前端性能监控通过埋点、数据采集、分析和可视化发现性能瓶颈并提供改进方向。其5个关键指标为:首屏加载时间、白屏时间、首次可交互时间(tti)、页面总加载时间和资源加载错误率。1. 首屏加载时间可在
中记录起始时间,在domcontentloaded事件后计算差值;2. 白屏时间通过mutationobserver监听dom变化并计算起始与首次渲染的时间差;3. tti可通过performancelongtasktiming与事件监听结合判断页面是否完全可交互;4. 页面总加载时间通过window.onload或performance api获取完整加载耗时;5. 资源加载错误率通过监听onerror事件统计资源加载失败比例。性能数据可通过fetch或xmlhttprequest发送至监控系统,以实现持续优化用户体验。
前端性能监控对于优化用户体验至关重要。它就像一个隐形的医生,默默守护着你的网站或应用,确保它运行流畅、响应迅速。
前端性能监控主要通过埋点、数据采集、分析和可视化来发现性能瓶颈,并提供改进方向。
前端性能监控的5个关键指标
立即学习“前端免费学习笔记(深入)”;
- 首屏加载时间: 用户第一眼看到页面的时间。
- 白屏时间: 从用户访问到页面开始显示内容的时间。
- 首次可交互时间 (TTI): 页面变得完全可交互的时间。
- 页面总加载时间: 加载所有资源所需的时间。
- 资源加载错误率: 页面资源加载失败的比例。
如何使用 JavaScript 监控首屏加载时间?
首屏加载时间是用户体验的黄金指标。你可以通过以下步骤使用 JavaScript 监控它:
- 在 中添加时间戳: 在 html 的 部分,尽可能靠前的位置,添加一个内联的 JavaScript 脚本,记录页面开始加载的时间。
<head> <script> window.performanceStartTime = new Date().getTime(); </script> ... </head>
- 在首屏内容加载完成后计算时间差: 在首屏内容加载完成后,通常是在 DOMContentLoaded 事件触发后,或者在首屏图片加载完成后,计算当前时间与 performanceStartTime 的差值。
document.addEventListener('DOMContentLoaded', function() { setTimeout(function() { // 延迟一段时间,确保首屏内容渲染完成 const now = new Date().getTime(); const firstScreenTime = now - window.performanceStartTime; console.log('首屏加载时间:', firstScreenTime + 'ms'); // 将数据发送到你的监控系统 sendPerformanceData({ firstScreenTime: firstScreenTime }); }, 500); // 延迟 500ms,根据实际情况调整 }); function sendPerformanceData(data) { // 使用 fetch 或 XMLHttpRequest 发送数据 fetch('/api/performance', { method: 'POST', headers: { 'Content-Type': 'application/JSon' }, body: JSON.stringify(data) }).then(response => { // 处理响应 }).catch(error => { console.error('发送性能数据失败:', error); }); }
- 考虑使用 Performance API: 更精确的方式是使用 Performance API,它可以提供更详细的性能数据,例如 DNS 查询时间、TCP 连接时间、请求响应时间等。
window.onload = function() { setTimeout(function() { const performance = window.performance; if (!performance) { console.log('Performance API 不可用'); return; } const timing = performance.timing; const firstPaint = timing.domContentLoadedEventEnd - timing.navigationStart; console.log('首屏渲染时间 (domContentLoadedEventEnd - navigationStart):', firstPaint + 'ms'); // 发送性能数据 sendPerformanceData({ firstPaint: firstPaint }); }, 500); };
注意事项:
- 延迟:setTimeout 的延迟时间需要根据实际情况调整,确保首屏内容已经渲染完成。
- 准确性:首屏的定义可能因应用而异,需要根据实际情况选择合适的时机计算时间差。
- 数据发送:sendPerformanceData 函数需要根据你的监控系统进行调整。
如何监控白屏时间?
白屏时间是指用户打开页面到看到任何内容的时间间隔。优化白屏时间能显著改善用户体验。
- 埋点: 在 标签中,紧跟在 之前插入一个内联 JavaScript 脚本,记录页面开始渲染的时间戳。
<head> <script> window.pageStartTime = new Date().getTime(); </script> </head>
- 计算白屏时间: 在页面首次渲染内容出现后(例如,在首个 DOM 元素渲染后),立即计算当前时间与 pageStartTime 的差值。可以使用 MutationObserver 监听 DOM 变化。
const observer = new MutationObserver(function(mutations) { if (document.body) { // 检查 body 是否存在,防止过早触发 const now = new Date().getTime(); const blankScreenTime = now - window.pageStartTime; console.log('白屏时间:', blankScreenTime + 'ms'); sendPerformanceData({ blankScreenTime: blankScreenTime }); observer.disconnect(); // 停止监听 } }); observer.observe(document.documentElement, { childList: true, subtree: true });
- 数据上报: 将计算得到的白屏时间发送到你的监控系统。
关键点:
- MutationObserver:用于监听 DOM 变化,一旦检测到页面开始渲染,立即计算白屏时间。
- observer.disconnect():停止监听,避免重复计算。
- 确保在 标签存在后才开始监听,避免在 body 标签还未加载时就触发。
首次可交互时间 (TTI) 如何准确测量?
TTI 是指页面变得完全可交互的时间,例如用户可以点击按钮、填写表单等。准确测量 TTI 比较复杂,因为它涉及到判断页面上的所有关键元素是否都已加载并可响应用户输入。
const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { console.log('Long Task:', entry.duration, entry.name, entry.startTime); // 可以将 Long Task 的信息发送到监控系统,用于分析 TTI }); }); observer.observe({ type: 'longtask', buffered: true });
- 结合事件监听: 监听关键元素的事件,例如按钮的 click 事件、输入框的 input 事件等,判断这些元素是否能够响应用户输入。
const interactiveElements = document.querySelectorAll('button, input, select, textarea'); let ttiDetected = false; interactiveElements.forEach(element => { element.addEventListener('click', function() { if (!ttiDetected) { ttiDetected = true; const now = new Date().getTime(); console.log('TTI:', now + 'ms'); sendPerformanceData({ tti: now }); } }); });
- 使用 Lighthouse 等工具: Lighthouse 可以自动测量 TTI,并提供详细的性能分析报告。
挑战:
- TTI 的定义比较模糊,需要根据实际应用场景进行调整。
- 准确判断页面是否完全可交互比较困难,需要综合考虑多种因素。
如何监控页面总加载时间和资源加载错误率?
页面总加载时间是指加载所有资源所需的时间。资源加载错误率是指页面资源加载失败的比例。
- 页面总加载时间: 使用 window.onload 事件或 Performance API 测量页面总加载时间。
window.onload = function() { const performance = window.performance; const timing = performance.timing; const pageLoadTime = timing.loadEventEnd - timing.navigationStart; console.log('页面总加载时间:', pageLoadTime + 'ms'); sendPerformanceData({ pageLoadTime: pageLoadTime }); };
- 资源加载错误率: 监听 window.onerror 事件和 img.onerror 等事件,记录资源加载失败的次数。
let errorCount = 0; window.onerror = function(message, source, lineno, colno, error) { console.error('资源加载错误:', message, source, lineno, colno, error); errorCount++; }; const images = document.querySelectorAll('img'); images.forEach(img => { img.onerror = function() { console.error('图片加载失败:', img.src); errorCount++; }; }); window.addEventListener('load', function() { const totalResources = document.querySelectorAll('link[rel="stylesheet"], script, img').length; const errorRate = errorCount / totalResources; console.log('资源加载错误率:', errorRate); sendPerformanceData({ errorRate: errorRate }); });
注意事项:
- 需要统计所有类型的资源加载错误,例如 css、JavaScript、图片等。
- 资源加载错误率应该尽可能低,否则会严重影响用户体验。
如何将性能数据发送到监控系统?
将性能数据发送到监控系统是性能监控的关键一步。可以使用 fetch 或 XMLHttpRequest 发送数据。
function sendPerformanceData(data) { fetch('/api/performance', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then(response => { if (!response.ok) { console.error('发送性能数据失败:', response.status); } }).catch(error => { console.error('发送性能数据失败:', error); }); }
关键点:
- 选择合适的 API 端点:/api/performance 只是一个示例,需要根据你的监控系统进行调整。
- 处理错误:需要处理数据发送失败的情况,例如网络错误、服务器错误等。
- 数据格式:确保数据格式与监控系统兼容。
通过上述方法,你可以使用 JavaScript 实现前端性能监控,并收集关键指标,从而优化你的网站或应用,提升用户体验。