|
| 1 | +// Script to measure Web Vitals for your site |
| 2 | +// Run this in the browser console or integrate into your app |
| 3 | + |
| 4 | +class WebVitalsMonitor { |
| 5 | + constructor() { |
| 6 | + this.metrics = { |
| 7 | + LCP: null, |
| 8 | + FCP: null, |
| 9 | + TTFB: null, |
| 10 | + TBT: null, |
| 11 | + CLS: null, |
| 12 | + }; |
| 13 | + this.tbtData = { |
| 14 | + fcpTime: 0, |
| 15 | + longTasks: [], |
| 16 | + }; |
| 17 | + } |
| 18 | + |
| 19 | + // Measure Largest Contentful Paint |
| 20 | + measureLCP() { |
| 21 | + return new Promise((resolve) => { |
| 22 | + const observer = new PerformanceObserver((list) => { |
| 23 | + const entries = list.getEntries(); |
| 24 | + const lastEntry = entries[entries.length - 1]; |
| 25 | + this.metrics.LCP = (lastEntry.renderTime || lastEntry.loadTime) / 1000; |
| 26 | + console.log('✅ LCP:', this.metrics.LCP.toFixed(2) + 's'); |
| 27 | + }); |
| 28 | + observer.observe({ type: 'largest-contentful-paint', buffered: true }); |
| 29 | + |
| 30 | + // LCP can change, so we'll resolve after a timeout |
| 31 | + setTimeout(() => resolve(this.metrics.LCP), 5000); |
| 32 | + }); |
| 33 | + } |
| 34 | + |
| 35 | + // Measure First Contentful Paint |
| 36 | + measureFCP() { |
| 37 | + return new Promise((resolve) => { |
| 38 | + const observer = new PerformanceObserver((list) => { |
| 39 | + const entries = list.getEntries(); |
| 40 | + entries.forEach((entry) => { |
| 41 | + if (entry.name === 'first-contentful-paint') { |
| 42 | + this.metrics.FCP = entry.startTime / 1000; |
| 43 | + this.tbtData.fcpTime = entry.startTime; |
| 44 | + console.log('✅ FCP:', this.metrics.FCP.toFixed(2) + 's'); |
| 45 | + resolve(this.metrics.FCP); |
| 46 | + } |
| 47 | + }); |
| 48 | + }); |
| 49 | + observer.observe({ type: 'paint', buffered: true }); |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | + // Measure Time to First Byte |
| 54 | + measureTTFB() { |
| 55 | + const navEntry = performance.getEntriesByType('navigation')[0]; |
| 56 | + if (navEntry) { |
| 57 | + this.metrics.TTFB = navEntry.responseStart / 1000; |
| 58 | + console.log('✅ TTFB:', this.metrics.TTFB.toFixed(2) + 's'); |
| 59 | + return this.metrics.TTFB; |
| 60 | + } |
| 61 | + return null; |
| 62 | + } |
| 63 | + |
| 64 | + // Measure Total Blocking Time |
| 65 | + measureTBT() { |
| 66 | + return new Promise((resolve) => { |
| 67 | + const observer = new PerformanceObserver((list) => { |
| 68 | + const entries = list.getEntries(); |
| 69 | + entries.forEach((entry) => { |
| 70 | + if (entry.startTime >= this.tbtData.fcpTime) { |
| 71 | + this.tbtData.longTasks.push({ |
| 72 | + duration: entry.duration, |
| 73 | + startTime: entry.startTime, |
| 74 | + }); |
| 75 | + } |
| 76 | + }); |
| 77 | + }); |
| 78 | + observer.observe({ type: 'longtask', buffered: true }); |
| 79 | + |
| 80 | + // Calculate TBT after page is interactive |
| 81 | + setTimeout(() => { |
| 82 | + let totalBlockingTime = 0; |
| 83 | + this.tbtData.longTasks.forEach((task) => { |
| 84 | + if (task.duration > 50) { |
| 85 | + totalBlockingTime += task.duration - 50; |
| 86 | + } |
| 87 | + }); |
| 88 | + this.metrics.TBT = totalBlockingTime / 1000; |
| 89 | + console.log('✅ TBT:', this.metrics.TBT.toFixed(2) + 's'); |
| 90 | + console.log(' Long tasks:', this.tbtData.longTasks.length); |
| 91 | + resolve(this.metrics.TBT); |
| 92 | + }, 5000); |
| 93 | + }); |
| 94 | + } |
| 95 | + |
| 96 | + // Measure Cumulative Layout Shift |
| 97 | + measureCLS() { |
| 98 | + return new Promise((resolve) => { |
| 99 | + let clsValue = 0; |
| 100 | + const observer = new PerformanceObserver((list) => { |
| 101 | + const entries = list.getEntries(); |
| 102 | + entries.forEach((entry) => { |
| 103 | + // Only count layout shifts without recent user input |
| 104 | + if (!entry.hadRecentInput) { |
| 105 | + clsValue += entry.value; |
| 106 | + } |
| 107 | + }); |
| 108 | + this.metrics.CLS = clsValue; |
| 109 | + }); |
| 110 | + observer.observe({ type: 'layout-shift', buffered: true }); |
| 111 | + |
| 112 | + // Observe for a while, then resolve |
| 113 | + setTimeout(() => { |
| 114 | + console.log('✅ CLS:', this.metrics.CLS.toFixed(3)); |
| 115 | + resolve(this.metrics.CLS); |
| 116 | + }, 5000); |
| 117 | + }); |
| 118 | + } |
| 119 | + |
| 120 | + // Get status for each metric |
| 121 | + getStatus(metric, value) { |
| 122 | + const thresholds = { |
| 123 | + LCP: { good: 2.5, needsImprovement: 4.0 }, |
| 124 | + FCP: { good: 1.8, needsImprovement: 3.0 }, |
| 125 | + TTFB: { good: 0.8, needsImprovement: 1.8 }, |
| 126 | + TBT: { good: 0.2, needsImprovement: 0.6 }, |
| 127 | + CLS: { good: 0.1, needsImprovement: 0.25 }, |
| 128 | + }; |
| 129 | + |
| 130 | + const t = thresholds[metric]; |
| 131 | + if (value <= t.good) return '🟢 Good'; |
| 132 | + if (value <= t.needsImprovement) return '🟡 Needs Improvement'; |
| 133 | + return '🔴 Critical'; |
| 134 | + } |
| 135 | + |
| 136 | + // Run all measurements |
| 137 | + async measureAll() { |
| 138 | + console.log('🚀 Starting Web Vitals measurement...\n'); |
| 139 | + |
| 140 | + // Measure TTFB immediately |
| 141 | + this.measureTTFB(); |
| 142 | + |
| 143 | + // Wait for paint metrics |
| 144 | + await this.measureFCP(); |
| 145 | + |
| 146 | + // Run LCP, TBT, and CLS in parallel |
| 147 | + await Promise.all([ |
| 148 | + this.measureLCP(), |
| 149 | + this.measureTBT(), |
| 150 | + this.measureCLS(), |
| 151 | + ]); |
| 152 | + |
| 153 | + this.displayResults(); |
| 154 | + return this.metrics; |
| 155 | + } |
| 156 | + |
| 157 | + // Display formatted results |
| 158 | + displayResults() { |
| 159 | + console.log('\n📊 Web Vitals Results:'); |
| 160 | + console.log('━'.repeat(60)); |
| 161 | + |
| 162 | + Object.entries(this.metrics).forEach(([metric, value]) => { |
| 163 | + if (value !== null) { |
| 164 | + const status = this.getStatus(metric, value); |
| 165 | + const unit = metric === 'CLS' ? '' : 's'; |
| 166 | + console.log(`${metric.padEnd(6)} | ${value.toFixed(metric === 'CLS' ? 3 : 2)}${unit.padEnd(2)} | ${status}`); |
| 167 | + } |
| 168 | + }); |
| 169 | + |
| 170 | + console.log('━'.repeat(60)); |
| 171 | + } |
| 172 | + |
| 173 | + // Export as markdown table |
| 174 | + exportAsMarkdown() { |
| 175 | + let markdown = '| Metric | Measured Value | Status |\n'; |
| 176 | + markdown += '| :--- | :--- | :--- |\n'; |
| 177 | + |
| 178 | + const metricNames = { |
| 179 | + LCP: 'LCP (Largest Contentful Paint)', |
| 180 | + FCP: 'FCP (First Contentful Paint)', |
| 181 | + TTFB: 'TTFB (Time to First Byte)', |
| 182 | + TBT: 'TBT (Total Blocking Time)', |
| 183 | + CLS: 'CLS (Cumulative Layout Shift)', |
| 184 | + }; |
| 185 | + |
| 186 | + Object.entries(this.metrics).forEach(([metric, value]) => { |
| 187 | + if (value !== null) { |
| 188 | + const name = metricNames[metric]; |
| 189 | + const unit = metric === 'CLS' ? '' : 's'; |
| 190 | + const status = this.getStatus(metric, value).replace(/[🟢🟡🔴] /, ''); |
| 191 | + markdown += `| **${name}** | ${value.toFixed(metric === 'CLS' ? 3 : 2)}${unit} | ${status} |\n`; |
| 192 | + } |
| 193 | + }); |
| 194 | + |
| 195 | + console.log('\n📝 Markdown Table:\n'); |
| 196 | + console.log(markdown); |
| 197 | + return markdown; |
| 198 | + } |
| 199 | +} |
| 200 | + |
| 201 | +// Usage: |
| 202 | +// const monitor = new WebVitalsMonitor(); |
| 203 | +// monitor.measureAll().then(metrics => { |
| 204 | +// monitor.exportAsMarkdown(); |
| 205 | +// }); |
| 206 | + |
| 207 | +// Auto-run if in browser |
| 208 | +if (typeof window !== 'undefined') { |
| 209 | + window.WebVitalsMonitor = WebVitalsMonitor; |
| 210 | + console.log('💡 Usage: const monitor = new WebVitalsMonitor(); await monitor.measureAll();'); |
| 211 | +} |
0 commit comments