Web Vitals & Performance (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
Measuring and Reporting RUM Web Vitals with the `web-vitals` Library.
senior LevelCode ExampleSystem Design
In Simple Words:
The official Google web-vitals library hooks into PerformanceObserver APIs to calculate Core Web Vitals (LCP, INP, CLS) in production and dispatch telemetry to analytics backends.
Code Example
javascript
import { onLCP, onINP, onCLS } from 'web-vitals';
function sendToAnalytics(metric) {
const body = JSON.stringify({
name: metric.name,
value: metric.value,
rating: metric.rating, // "good" | "needs-improvement" | "poor"
delta: metric.delta,
id: metric.id,
});
// Non-blocking beacon transmission
navigator.sendBeacon('/api/vitals', body);
}
onLCP(sendToAnalytics);
onINP(sendToAnalytics);
onCLS(sendToAnalytics);