A comprehensive guide to Core Web Vitals - Google's essential metrics for measuring user experience, including Largest Contentful Paint (LCP), First Input Delay (FID), and Cumulative Layout Shift (CLS).
Core Web Vitals are a set of specific factors that Google considers important in a webpage's overall user experience. These metrics measure real-world user experience for loading performance, interactivity, and visual stability of web pages.
Measures loading performance and marks the point when the largest content element becomes visible:
| Rating | LCP Time | Description |
|---|---|---|
| Good | ⤠2.5 seconds | Fast loading experience |
| Needs Improvement | 2.5 - 4.0 seconds | Moderate loading experience |
| Poor | > 4.0 seconds | Slow loading experience |
Measures interactivity and quantifies the delay between user interaction and browser response:
| Rating | FID Time | Description |
|---|---|---|
| Good | ⤠100 milliseconds | Responsive to user input |
| Needs Improvement | 100 - 300 milliseconds | Moderately responsive |
| Poor | > 300 milliseconds | Unresponsive to user input |
Measures visual stability and quantifies unexpected layout shifts:
| Rating | CLS Score | Description |
|---|---|---|
| Good | ⤠0.1 | Minimal unexpected layout shifts |
| Needs Improvement | 0.1 - 0.25 | Some layout shifts |
| Poor | > 0.25 | Significant layout shifts |
// Core Web Vitals measurement implementation
class CoreWebVitalsMonitor {
constructor() {
this.metrics = {
lcp: null,
fid: null,
cls: 0
};
this.init();
}
init() {
this.measureLCP();
this.measureFID();
this.measureCLS();
}
measureLCP() {
new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1];
this.metrics.lcp = lastEntry.startTime;
this.reportMetric('lcp', lastEntry.startTime);
}).observe({ entryTypes: ['largest-contentful-paint'] });
}
measureFID() {
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
const fid = entry.processingStart - entry.startTime;
this.metrics.fid = fid;
this.reportMetric('fid', fid);
}
}).observe({ entryTypes: ['first-input'] });
}
measureCLS() {
let clsValue = 0;
let sessionValue = 0;
let sessionEntries = [];
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
// Only count layout shifts without recent input
if (!entry.hadRecentInput) {
const firstSessionEntry = sessionEntries[0];
const lastSessionEntry = sessionEntries[sessionEntries.length - 1];
// If the entry occurred less than 1 second after the previous entry
// and less than 5 seconds after the first entry in the session,
// include it in the current session
if (sessionValue &&
entry.startTime - lastSessionEntry.startTime < 1000 &&
entry.startTime - firstSessionEntry.startTime < 5000) {
sessionValue += entry.value;
sessionEntries.push(entry);
} else {
sessionValue = entry.value;
sessionEntries = [entry];
}
// If the current session value is larger than the current CLS value,
// update CLS and the entries contributing to it
if (sessionValue > clsValue) {
clsValue = sessionValue;
this.metrics.cls = clsValue;
this.reportMetric('cls', clsValue);
}
}
}
}).observe({ entryTypes: ['layout-shift'] });
}
reportMetric(name, value) {
const rating = this.getRating(name, value);
console.log(`${name.toUpperCase()}: ${value} (${rating})`);
// Send to analytics
this.sendToAnalytics({
metric: name,
value: value,
rating: rating,
url: window.location.href,
timestamp: Date.now()
});
}
getRating(metric, value) {
const thresholds = {
lcp: { good: 2500, poor: 4000 },
fid: { good: 100, poor: 300 },
cls: { good: 0.1, poor: 0.25 }
};
const threshold = thresholds[metric];
if (value <= threshold.good) return 'good';
if (value <= threshold.poor) return 'needs-improvement';
return 'poor';
}
sendToAnalytics(data) {
// Implementation for sending data to analytics service
if (navigator.sendBeacon) {
navigator.sendBeacon('/api/web-vitals', JSON.stringify(data));
}
}
getReport() {
return {
lcp: {
value: this.metrics.lcp,
rating: this.metrics.lcp ? this.getRating('lcp', this.metrics.lcp) : null
},
fid: {
value: this.metrics.fid,
rating: this.metrics.fid ? this.getRating('fid', this.metrics.fid) : null
},
cls: {
value: this.metrics.cls,
rating: this.getRating('cls', this.metrics.cls)
}
};
}
}
// Initialize monitoring
const webVitalsMonitor = new CoreWebVitalsMonitor();// LCP optimization strategies
class LCPOptimizer {
constructor() {
this.criticalResources = [];
this.init();
}
init() {
this.identifyLCPElement();
this.optimizeResourceLoading();
this.implementPreloading();
}
identifyLCPElement() {
new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1];
// Mark LCP element for optimization
if (lastEntry.element) {
lastEntry.element.classList.add('lcp-element');
this.optimizeLCPElement(lastEntry.element);
}
}).observe({ entryTypes: ['largest-contentful-paint'] });
}
optimizeLCPElement(element) {
if (element.tagName === 'IMG') {
this.optimizeImage(element);
} else if (element.tagName === 'VIDEO') {
this.optimizeVideo(element);
} else {
this.optimizeText(element);
}
}
optimizeImage(img) {
// Ensure image is preloaded
if (!img.loading || img.loading !== 'eager') {
img.loading = 'eager';
}
// Add to critical resources for preloading
this.criticalResources.push({
href: img.src,
as: 'image',
type: 'preload'
});
// Optimize image format and size
this.optimizeImageFormat(img);
}
optimizeImageFormat(img) {
// Check if modern formats are supported
const supportsWebP = this.supportsFormat('webp');
const supportsAVIF = this.supportsFormat('avif');
if (supportsAVIF || supportsWebP) {
this.replaceWithModernFormat(img, supportsAVIF ? 'avif' : 'webp');
}
}
supportsFormat(format) {
const canvas = document.createElement('canvas');
return canvas.toDataURL(`image/${format}`).indexOf(`data:image/${format}`) === 0;
}
replaceWithModernFormat(img, format) {
const modernSrc = img.src.replace(/\.(jpg|jpeg|png)$/i, `.${format}`);
// Test if modern format exists
const testImg = new Image();
testImg.onload = () => {
img.src = modernSrc;
};
testImg.onerror = () => {
// Keep original format if modern format doesn't exist
};
testImg.src = modernSrc;
}
implementPreloading() {
this.criticalResources.forEach(resource => {
const link = document.createElement('link');
link.rel = resource.type;
link.as = resource.as;
link.href = resource.href;
if (resource.as === 'font') {
link.crossOrigin = 'anonymous';
}
document.head.appendChild(link);
});
}
}// FID optimization strategies
class FIDOptimizer {
constructor() {
this.taskQueue = [];
this.isProcessing = false;
this.init();
}
init() {
this.implementCodeSplitting();
this.optimizeMainThread();
this.deferNonCriticalJS();
}
// Break up long tasks
scheduleTask(task, priority = 'normal') {
this.taskQueue.push({ task, priority });
if (!this.isProcessing) {
this.processTaskQueue();
}
}
async processTaskQueue() {
this.isProcessing = true;
while (this.taskQueue.length > 0) {
// Sort by priority
this.taskQueue.sort((a, b) => {
const priorities = { high: 3, normal: 2, low: 1 };
return priorities[b.priority] - priorities[a.priority];
});
const { task } = this.taskQueue.shift();
// Use scheduler API if available, otherwise setTimeout
if ('scheduler' in window && 'postTask' in scheduler) {
await scheduler.postTask(task);
} else {
await new Promise(resolve => {
setTimeout(() => {
task();
resolve();
}, 0);
});
}
// Yield to browser if needed
if (this.shouldYield()) {
await this.yieldToMain();
}
}
this.isProcessing = false;
}
shouldYield() {
return performance.now() % 50 === 0; // Yield every 50ms
}
yieldToMain() {
return new Promise(resolve => {
setTimeout(resolve, 0);
});
}
// Defer non-critical JavaScript
deferNonCriticalJS() {
const scripts = document.querySelectorAll('script[data-defer]');
scripts.forEach(script => {
const newScript = document.createElement('script');
newScript.src = script.src;
newScript.defer = true;
// Load after main content
window.addEventListener('load', () => {
document.head.appendChild(newScript);
});
script.remove();
});
}
// Optimize event handlers
optimizeEventHandlers() {
// Use passive event listeners where possible
const passiveEvents = ['touchstart', 'touchmove', 'wheel', 'scroll'];
passiveEvents.forEach(eventType => {
document.addEventListener(eventType, (e) => {
// Event handler logic
}, { passive: true });
});
// Debounce expensive operations
const debouncedResize = this.debounce(() => {
// Resize logic
}, 250);
window.addEventListener('resize', debouncedResize);
}
debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
}// CLS optimization strategies
class CLSOptimizer {
constructor() {
this.init();
}
init() {
this.reserveSpaceForImages();
this.reserveSpaceForAds();
this.optimizeFontLoading();
this.handleDynamicContent();
}
reserveSpaceForImages() {
const images = document.querySelectorAll('img:not([width]):not([height])');
images.forEach(img => {
// Set aspect ratio to prevent layout shift
if (img.dataset.aspectRatio) {
const aspectRatio = parseFloat(img.dataset.aspectRatio);
img.style.aspectRatio = aspectRatio;
} else {
// Calculate aspect ratio from natural dimensions
img.onload = () => {
const aspectRatio = img.naturalWidth / img.naturalHeight;
img.style.aspectRatio = aspectRatio;
};
}
});
}
reserveSpaceForAds() {
const adSlots = document.querySelectorAll('.ad-slot');
adSlots.forEach(slot => {
// Set minimum height for ad slots
const minHeight = slot.dataset.minHeight || '250px';
slot.style.minHeight = minHeight;
// Add placeholder content
if (!slot.innerHTML.trim()) {
slot.innerHTML = 'Advertisement';
}
});
}
optimizeFontLoading() {
// Use font-display: swap for web fonts
const fontFaces = document.styleSheets;
Array.from(fontFaces).forEach(sheet => {
try {
Array.from(sheet.cssRules).forEach(rule => {
if (rule instanceof CSSFontFaceRule) {
if (!rule.style.fontDisplay) {
rule.style.fontDisplay = 'swap';
}
}
});
} catch (e) {
// Handle cross-origin stylesheets
}
});
// Preload critical fonts
this.preloadCriticalFonts();
}
preloadCriticalFonts() {
const criticalFonts = [
'/fonts/main-font.woff2',
'/fonts/heading-font.woff2'
];
criticalFonts.forEach(fontUrl => {
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'font';
link.type = 'font/woff2';
link.crossOrigin = 'anonymous';
link.href = fontUrl;
document.head.appendChild(link);
});
}
handleDynamicContent() {
// Use transform instead of changing layout properties
const animatedElements = document.querySelectorAll('.animated');
animatedElements.forEach(el => {
// Prefer transform and opacity for animations
el.style.willChange = 'transform, opacity';
// Use transform instead of changing top/left
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'attributes') {
const target = mutation.target;
// Convert position changes to transforms
if (mutation.attributeName === 'style') {
this.convertToTransform(target);
}
}
});
});
observer.observe(el, {
attributes: true,
attributeFilter: ['style']
});
});
}
convertToTransform(element) {
const computedStyle = getComputedStyle(element);
const left = parseFloat(computedStyle.left) || 0;
const top = parseFloat(computedStyle.top) || 0;
if (left !== 0 || top !== 0) {
element.style.left = '0';
element.style.top = '0';
element.style.transform = `translate(${left}px, ${top}px)`;
}
}
// Monitor layout shifts in development
monitorLayoutShifts() {
if (process.env.NODE_ENV === 'development') {
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!entry.hadRecentInput && entry.value > 0.1) {
console.warn('Large layout shift detected:', {
value: entry.value,
sources: entry.sources,
startTime: entry.startTime
});
// Highlight shifted elements
entry.sources.forEach(source => {
if (source.node) {
source.node.style.outline = '2px solid red';
setTimeout(() => {
source.node.style.outline = '';
}, 3000);
}
});
}
}
}).observe({ entryTypes: ['layout-shift'] });
}
}
}// Lighthouse CI configuration for Core Web Vitals
module.exports = {
ci: {
collect: {
numberOfRuns: 3,
settings: {
chromeFlags: '--no-sandbox --disable-dev-shm-usage'
}
},
assert: {
assertions: {
'categories:performance': ['error', { minScore: 0.9 }],
'largest-contentful-paint': ['error', { maxNumericValue: 2500 }],
'first-input-delay': ['error', { maxNumericValue: 100 }],
'cumulative-layout-shift': ['error', { maxNumericValue: 0.1 }],
'first-contentful-paint': ['error', { maxNumericValue: 1800 }],
'speed-index': ['error', { maxNumericValue: 3400 }],
'interactive': ['error', { maxNumericValue: 3800 }]
}
},
upload: {
target: 'temporary-public-storage'
}
}
};
// Web Vitals testing with Playwright
const { test, expect } = require('@playwright/test');
test('Core Web Vitals', async ({ page }) => {
await page.goto('/');
// Measure Core Web Vitals
const vitals = await page.evaluate(() => {
return new Promise((resolve) => {
const metrics = {};
let metricsCount = 0;
// LCP
new PerformanceObserver((list) => {
const entries = list.getEntries();
metrics.lcp = entries[entries.length - 1].startTime;
metricsCount++;
if (metricsCount === 2) resolve(metrics); // FID might not fire
}).observe({ entryTypes: ['largest-contentful-paint'] });
// CLS
let clsValue = 0;
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!entry.hadRecentInput) {
clsValue += entry.value;
}
}
metrics.cls = clsValue;
metricsCount++;
if (metricsCount === 2) resolve(metrics);
}).observe({ entryTypes: ['layout-shift'] });
// Timeout after 10 seconds
setTimeout(() => resolve(metrics), 10000);
});
});
// Assert Core Web Vitals thresholds
expect(vitals.lcp).toBeLessThan(2500);
expect(vitals.cls).toBeLessThan(0.1);
});Explore these comprehensive pillar articles related to Core Web Vitals
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
Comprehensive guide to triadic color schemes - three colors evenly spaced around the color wheel that create balanced, vibrant, and dynamic visual compositions with mathematical precision and artistic appeal.
Discover more about Core Web Vitals and related color theory concepts
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
A comprehensive guide to monochromatic color schemes - sophisticated single-hue harmonies that create unified visual experiences through systematic variations in saturation, lightness, and tonal relationships, essential for elegant design compositions, brand consistency, and advanced color theory applications requiring cohesive aesthetic unity.
A comprehensive guide to split-complementary color schemes - sophisticated three-color harmonies that combine a base color with two colors adjacent to its complement, creating balanced visual contrast with reduced tension compared to direct complementary pairs, essential for refined design compositions, brand identity systems, and advanced color theory applications.
A comprehensive guide to tetradic color schemes - sophisticated four-color harmonies that use two complementary pairs arranged in rectangular or square formations on the color wheel, providing maximum color variety while maintaining structured relationships essential for dynamic design compositions, brand systems, and advanced color theory applications.
Discover more color terminology and concepts in our comprehensive glossary.
Browse Full Glossary