Measuring Metrics
Measuring Core Web Vitals¶
Core Web Vitals are critical metrics that define user experience on the web. To optimize performance, developers must measure these metrics using tools like Lighthouse, Chrome DevTools, and the Web Vitals library. Each tool provides unique insights into loading performance, interactivity, and visual stability.
## Lighthouse: Comprehensive Audit Tool¶
Lighthouse is a Chrome DevTools-based auditing tool that evaluates Core Web Vitals (LCP, FID, CLS) and provides actionable recommendations.
๐ Running Lighthouse¶
Use the CLI or DevTools to audit a site:
Example Output:
{
"audits": {
"first-contentful-paint": {
"score": 0.95,
"details": { "metric": "LCP", "value": 2300 }
}
}
}
๐ Lighthouse Metrics¶
- LCP (Loading Performance): Measures time to render the first contentful paint.
- FID (Interactivity): Tracks time until first input is processed.
- CLS (Visual Stability): Quantifies layout shifts.
Diagram: Lighthouse Audit Interface (https://developers.google.com/web/tools/lighthouse)
## Chrome DevTools: Real-Time Performance Analysis¶
Chrome DevTools provides granular insights into Core Web Vitals during runtime.
๐ Performance Tab Workflow¶
- Open DevTools > Performance tab.
- Click Record and load the page.
- Analyze the Metrics section for LCP, FID, and CLS.
Example:
- LCP: Look for the first contentful paint in the Waterfall timeline.
- FID: Check the User Timing section for input delays.
- CLS: Use the Layout Shifts panel to identify unstable elements.
๐งช Using the Performance API¶
Programmatically access metrics with the Performance API:
performance.getEntriesByType('layout-shift').forEach(entry => {
console.log(`CLS: ${entry.metrics.layoutShift.value.toFixed(2)}px`);
});
Diagram: Chrome DevTools Performance Tab (https://developer.chrome.com/docs/devtools/performance/)
## Web Vitals Library: Client-Side Tracking¶
The Web Vitals library allows developers to track Core Web Vitals directly in the browser.
๐ฆ Installation and Setup¶
import { onLCP, onFID, onCLS } from 'web-vitals';
onLCP((metric) => {
console.log(`LCP: ${metric.value.toFixed(2)}ms`);
});
onFID((metric) => {
console.log(`FID: ${metric.value.toFixed(2)}ms`);
});
onCLS((metric) => {
console,log(`CLS: ${metric.value.toFixed(2)}px`);
});
๐ Metrics Details¶
- LCP: Measures time to first contentful paint.
- FID: Tracks time until first input is processed.
- CLS: Quantifies layout shifts.
Example: Logging FID for a React app:
Key takeaways¶
- Use Lighthouse for automated audits and benchmarking.
- Leverage Chrome DevTools for real-time, granular analysis.
- Integrate the Web Vitals library for client-side tracking and custom alerts.
- Combine all tools to identify bottlenecks and validate optimizations.
- Prioritize LCP, FID, and CLS to ensure a seamless user experience.