By : admin
Language: javascript
Date Published: 1 month ago
Core Web Vitals are now table stakes for search visibility and user retention, especially in high-traffic finance or e‑commerce apps. Google focuses on three metrics: Largest Contentful Paint (LCP), Interaction to Next Paint (INP), and Cumulative Layout Shift (CLS), with recommended thresholds of 2.5s, 200ms, and 0.1 respectively.
On mature React codebases, the fastest wins usually come from targeting these directly instead of generic “optimize everything” efforts. For LCP, serve the hero content via SSR/SSG, preload the main image/font, and avoid lazy-loading above-the-fold assets. For INP, break up long tasks, aggressively code-split routes, and move rarely used logic behind dynamic imports. For CLS, always reserve space for images/ads, use font-display: swap, and avoid DOM insertions above the fold after initial paint.
Treat performance as a feature: define budgets (e.g., max JS per route), add Lighthouse/WebPageTest checks to CI, and monitor Core Web Vitals via Search Console or RUM tooling. In a 4‑year-old frontend, disciplined incremental changes like these usually outperform big-bang rewrites while still delivering tangible user-facing improvements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | // Example: Targeted Core Web Vitals fixes in a React/Next.js page // app/layout.tsx (Next.js App Router) – prioritize fonts and main CSS export const metadata = { title: "High-Performance Product Page", }; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en"> <head> {/* Improve LCP: preload main font and hero image */} <link rel="preload" href="/fonts/Inter-regular.woff2" as="font" type="font/woff2" crossOrigin="anonymous" /> <link rel="preload" as="image" href="/images/hero-product.webp" /> </head> <body>{children}</body> </html> ); } // app/product/[id]/page.tsx – SSR the hero, avoid layout shift, split heavy JS import Image from "next/image"; import dynamic from "next/dynamic"; // Heavy widget (charts, rich reviews) loaded after interaction const ReviewsWidget = dynamic(() => import("../../components/ReviewsWidget"), { ssr: false, loading: () => <p>Loading reviews…</p>, }); // Simulated API call async function fetchProduct(id: string) { const res = await fetch(`https://api.example.com/products/${id}`, { // Cache for 60s, helps LCP by serving static-ish HTML next: { revalidate: 60 }, }); if (!res.ok) throw new Error("Failed to fetch product"); return res.json(); } export default async function ProductPage({ params }: { params: { id: string } }) { const product = await fetchProduct(params.id); return ( <main className="page"> {/* Hero section – critical for LCP */} <section className="hero"> {/* Reserve space explicitly → better CLS */} <div className="hero-media"> <Image src={product.heroImageUrl} alt={product.name} width={800} height={600} priority /> </div> <div className="hero-content"> <h1>{product.name}</h1> <p>{product.subtitle}</p> <p className="price">${product.price}</p> <button className="primary">Add to cart</button> </div> </section> {/* Below-the-fold content can be lazy-loaded */} <section className="details"> <h2>Details</h2> <p>{product.description}</p> </section> {/* Heavy interactive widget loaded after initial paint → better INP/TBT */} <section className="reviews"> <h2>Customer reviews</h2> <ReviewsWidget productId={product.id} /> </section> </main> ); } // components/ReviewsWidget.tsx – split long tasks, avoid main-thread blocking "use client"; import { useEffect, useState, useTransition } from "react"; type Review = { id: string; user: string; rating: number; comment: string; }; export default function ReviewsWidget({ productId }: { productId: string }) { const [reviews, setReviews] = useState<Review[]>([]); const [isPending, startTransition] = useTransition(); useEffect(() => { let cancelled = false; async function load() { const res = await fetch(`/api/reviews?productId=${productId}`); const data = (await res.json()) as Review[]; // Use startTransition for non-urgent updates to help INP startTransition(() => { if (!cancelled) setReviews(data); }); } load(); return () => { cancelled = true; }; }, [productId]); return ( <div className="reviews-widget"> {isPending && <p>Loading…</p>} {reviews.map((r) => ( <article key={r.id} className="review"> <header> <strong>{r.user}</strong> – <span>{r.rating} / 5</span> </header> <p>{r.comment}</p> </article> ))} </div> ); } // styles.css – minimal example of layout-stable styles /* .page { max-width: 1120px; margin: 0 auto; padding: 1.5rem; } .hero { display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(0, 0.9fr); gap: 2rem; align-items: center; } .hero-media { /* Explicit height via aspect ratio, improves CLS */ aspect-ratio: 4 / 3; position: relative; } .hero-content h1 { font-size: 2rem; margin-bottom: 0.75rem; } .price { font-size: 1.5rem; font-weight: 600; margin: 0.5rem 0 1rem; } .primary { padding: 0.75rem 1.5rem; border-radius: 999px; border: none; background: #111827; color: white; cursor: pointer; } .details, .reviews { margin-top: 2.5rem; } .review + .review { margin-top: 1rem; } */ |