Web Vitals JavaScript Library
What you'll learn: How to use Google's official web-vitals library to easily measure Core Web Vitals and other performance metrics in your web application.
Why Use the Web Vitals Library?
You've learned about the Performance Observer API, Long Tasks API, and various timing APIs—but measuring metrics like LCP, FID, and CLS correctly requires complex calculations and edge-case handling. Google's web-vitals library does all the heavy lifting for you, providing accurate, field-tested implementations of these measurements.
Think of it like using a professional thermometer instead of building your own temperature sensor—it's calibrated, reliable, and follows the exact specifications.
Installing the Library
npm install web-vitals
Or use a CDN for quick testing:
<script type="module">
import {onLCP, onFID, onCLS} from 'https://unpkg.com/web-vitals@3?module';
</script>
Measuring Core Web Vitals
The library provides simple callback functions for each metric:
import {onLCP, onFID, onCLS, onINP, onFCP, onTTFB} from 'web-vitals';
// Measure Largest Contentful Paint
onLCP(metric => {
console.log('LCP:', metric.value);
// Send to analytics
});
// Measure First Input Delay
onFID(metric => {
console.log('FID:', metric.value);
});
// Measure Cumulative Layout Shift
onCLS(metric => {
console.log('CLS:', metric.value);
});
// Measure newer metrics
onINP(metric => {
console.log('INP:', metric.value);
});
Each callback receives a metric object containing the value, name, id, and other useful properties. The library handles all the complexity of Performance Observers, timing calculations, and specification compliance.
Key Takeaway: The web-vitals library simplifies performance monitoring by providing ready-to-use functions that accurately measure LCP, FID, CLS, and other Web Vitals, eliminating the need to manually implement complex measurement logic.