Copy-paste solutions for every Core Web Vital issue. Each snippet is tested, framework-aware, and ready to ship.
Preloading your hero/LCP image drastically reduces discovery time, typically improving LCP by 500ms–1.5s.
<!-- Add in <head> before any stylesheets -->
<link rel="preload"
as="image"
href="/hero.avif"
type="image/avif"
fetchpriority="high"
imagesrcset="/hero-640.avif 640w, /hero-1024.avif 1024w, /hero-1920.avif 1920w"
imagesizes="100vw">
<!-- And set fetchpriority on the <img> itself -->
<img src="/hero.avif"
alt="Product hero"
width="1920" height="1080"
fetchpriority="high" />
Always set width/height (or aspect-ratio) so the browser can reserve layout space before the asset arrives.
// Always provide width + height attributes
<img src="/cover.jpg" alt="" width={1280} height={720} />
/* Or via CSS for fluid containers */
.media { aspect-ratio: 16 / 9; width: 100%; background: #111; }
.embed-wrap { min-height: 360px; }
Use scheduler.yield() (or postTask) to split work and keep INP under 200ms even during heavy renders.
// Yield between chunks of work
export async function yieldToMain() {
if ('scheduler' in window && 'yield' in scheduler) {
return scheduler.yield()
}
return new Promise((r) => setTimeout(r, 0))
}
export async function chunked<T>(items: T[], step: (i: T) => void) {
for (let i = 0; i < items.length; i++) {
step(items[i])
if (i % 50 === 0) await yieldToMain()
}
}
Serve cached HTML instantly while revalidating in the background. Slashes TTFB on dynamic pages.
// Next.js / Vercel edge
export const config = { matcher: '/((?!_next).*)' }
export function middleware(req: Request) {
const res = NextResponse.next()
res.headers.set(
'Cache-Control',
'public, s-maxage=60, stale-while-revalidate=86400'
)
return res
}
Defer below-the-fold media so the browser spends its first seconds on critical assets only.
<img src="/product-12.jpg"
alt="Product 12"
width={800} height={600}
loading="lazy"
decoding="async" />
<iframe src="https://www.youtube.com/embed/abc"
loading="lazy"
title="Demo video"
width="560" height="315"></iframe>
A locked-down CSP eliminates entire classes of XSS and clickjacking attacks in one header.
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-{random}';
img-src 'self' data: https:;
style-src 'self' 'unsafe-inline';
connect-src 'self' https://api.example.com;
frame-ancestors 'none';