Performance optimization
Optimize web performance for faster loading and better user experience.
How to use it
Claude Code
- Run the line below. It pulls the whole folder into
~/.claude/skills/performance. - Describe your job in plain words. Claude Code follows the skill from there.
npx degit addyosmani/web-quality-skills/skills/performance#main ~/.claude/skills/performanceFor one project only, change the path to .claude/skills/performance.
Claude (web or desktop app)
- On this page open ⋯ → Download .md.
- Save it as SKILL.md in a folder, zip the folder, then Customize → Skills → + → Create skill → Upload a skill.
- Pick the file and Save. Claude shows the name and description and runs a security scan.
- Check the skill is switched on.
- Start a new chat and describe your job in plain words. The AI follows the skill from there.
ChatGPT or another app
- ChatGPT: make a Project and paste it into Instructions.
- Neither? Paste it at the top of a new chat — it works for that chat.
Not working?
- Check which app you pasted it into — the steps above name the right one.
- Some skills need the paid tier of Claude or ChatGPT.
Paste into Claude, ChatGPT or Cursor.
Source of Performance optimization
Show the full text400 lines
| name | description | license | metadata |
|---|---|---|---|
| performance | Optimize web performance for faster loading and better user experience. Use when asked to "speed up my site", "optimize performance", "reduce load time", "fix slow loading", "improve page speed", or "performance audit". | MIT | author: web-quality-skills version: "2.0 |
Performance optimization
Evidence-led performance optimization using real-user signals for prioritization and browser traces for diagnosis. Focuses on loading speed, runtime responsiveness, and resource delivery.
How it works
- If a page can run, read the measurement workflow and establish a field-plus-lab baseline before editing.
- Prioritize poor real-user Core Web Vitals. Use a DevTools performance trace and its focused insights to find the cause.
- Inspect and change only the code or assets connected to measured bottlenecks.
- Re-run equivalent lab measurements and report before/after values, conditions, and uncertainty. Field verification remains pending until enough new user data arrives.
When no runnable page exists, perform static inspection but call findings hypotheses, not measured regressions. Include the command or browser workflow that can verify each high-impact hypothesis.
Prefer a browser tool that records a performance trace and exposes focused insights. With Chrome DevTools MCP, use performance_start_trace and performance_analyze_insight; do not route performance through lighthouse_audit, which covers non-performance Lighthouse categories.
Starting performance budget
Budgets must reflect the product's target devices, networks, page types, and user journeys. The values below are initial guardrails for a typical content or commerce page, not universal pass/fail criteria. Preserve an existing project budget when one is already defined.
| Resource | Budget | Rationale |
|---|---|---|
| Total page weight | < 1.5 MB | Bounds transfer time and data cost on constrained target networks; calibrate with representative pages |
| JavaScript (compressed) | < 300 KB | Protect parse and execution cost |
| CSS (compressed) | < 100 KB | Limit render-blocking work |
| Images (above-fold) | < 500 KB | Protect likely LCP resources |
| Fonts | < 100 KB | Limit critical font transfer |
| Third-party | < 200 KB | Bound code outside product control |
Critical rendering path
Server response
- TTFB < 800ms. Time to First Byte should be fast. Use CDN, caching, and efficient backends.
- Enable compression. Gzip or Brotli for text assets. Brotli preferred (15-20% smaller).
- HTTP/2 or HTTP/3. Multiplexing reduces connection overhead.
- Edge caching. Cache HTML at CDN edge when possible.
- Consider Early Hints (HTTP 103) for measured document latency. If a trace shows slow HTML generation and stable critical subresources, send an interim
103withLinkheaders before the normal final response from the same request. Use HTTP/2 or later. A CDN may synthesize the103fromLinkheaders on an earlier200, or the origin/edge handler can emit it directly. Unsupported clients continue to the final response, but confirm current browser and infrastructure support. Limit hints to proven critical preloads or preconnects: inaccurate hints waste bandwidth. Cloudflare reported a 20–30% LCP improvement in an artificial, image-heavy test; treat that as a vendor case study, not an expected saving, and measure your result. See MDN's 103 implementation example and the Cloudflare study.
Resource loading
Preconnect to required origins:
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://cdn.example.com" crossorigin>
Preload critical resources:
Preload only resources whose late discovery is visible in the trace. Each preload competes for bandwidth and an unnecessary high-priority request can delay LCP.
<!-- LCP image -->
<link rel="preload" href="/hero.webp" as="image" fetchpriority="high">
<!-- Critical font -->
<link rel="preload" href="/font.woff2" as="font" type="font/woff2" crossorigin>
Prerender likely-next navigations with the Speculation Rules API:
<script type="speculationrules">
{
"prerender": [{
"where": { "href_matches": "/*" },
"eagerness": "moderate"
}]
}
</script>
moderate waits for a stronger intent signal than eager modes. Measure prediction hit rate, transferred bytes, and server cost; a wrong prerender is roughly an unused navigation. See core-web-vitals → LCP for the tradeoffs and the prerenderingchange gating needed for analytics.
Defer non-critical CSS:
<!-- Critical CSS inlined -->
<style>/* Above-fold styles */</style>
<!-- Non-critical CSS -->
<link rel="preload" href="/styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/styles.css"></noscript>
JavaScript optimization
Defer non-essential scripts:
<!-- Parser-blocking (avoid) -->
<script src="/critical.js"></script>
<!-- Deferred (preferred) -->
<script defer src="/app.js"></script>
<!-- Async (for independent scripts) -->
<script async src="/analytics.js"></script>
<!-- Module (deferred by default) -->
<script type="module" src="/app.mjs"></script>
Code splitting patterns:
// Route-based splitting
const Dashboard = lazy(() => import('./Dashboard'));
// Component-based splitting
const HeavyChart = lazy(() => import('./HeavyChart'));
// Feature-based splitting
if (user.isPremium) {
const PremiumFeatures = await import('./PremiumFeatures');
}
Tree shaking best practices:
// ❌ Imports entire library
import _ from 'lodash';
_.debounce(fn, 300);
// ✅ Imports only what's needed
import debounce from 'lodash/debounce';
debounce(fn, 300);
Image optimization
Format selection
| Format | Use case | Browser support |
|---|---|---|
| AVIF | Photos, best compression | 92%+ |
| WebP | Photos, good fallback | 97%+ |
| PNG | Graphics with transparency | Universal |
| SVG | Icons, logos, illustrations | Universal |
Responsive images
<picture>
<!-- AVIF for modern browsers -->
<source
type="image/avif"
srcset="hero-400.avif 400w,
hero-800.avif 800w,
hero-1200.avif 1200w"
sizes="(max-width: 600px) 100vw, 50vw">
<!-- WebP fallback -->
<source
type="image/webp"
srcset="hero-400.webp 400w,
hero-800.webp 800w,
hero-1200.webp 1200w"
sizes="(max-width: 600px) 100vw, 50vw">
<!-- JPEG fallback -->
<img
src="hero-800.jpg"
srcset="hero-400.jpg 400w,
hero-800.jpg 800w,
hero-1200.jpg 1200w"
sizes="(max-width: 600px) 100vw, 50vw"
width="1200"
height="600"
alt="Hero image"
loading="lazy"
decoding="async">
</picture>
LCP image priority
<!-- Above-fold LCP image: eager loading, high priority -->
<img
src="hero.webp"
fetchpriority="high"
loading="eager"
decoding="sync"
alt="Hero">
<!-- Below-fold images: lazy loading -->
<img
src="product.webp"
loading="lazy"
decoding="async"
alt="Product">
Font optimization
Loading strategy
/* System font stack as fallback */
body {
font-family: 'Custom Font', -apple-system, BlinkMacSystemFont,
'Segoe UI', Roboto, sans-serif;
}
/* Prevent invisible text */
@font-face {
font-family: 'Custom Font';
src: url('/fonts/custom.woff2') format('woff2');
font-display: swap; /* or optional for non-critical */
font-weight: 400;
font-style: normal;
unicode-range: U+0000-00FF; /* Subset to Latin */
}
Preloading critical fonts
<link rel="preload" href="/fonts/heading.woff2" as="font" type="font/woff2" crossorigin>
Variable fonts
/* One file instead of multiple weights */
@font-face {
font-family: 'Inter';
src: url('/fonts/Inter-Variable.woff2') format('woff2-variations');
font-weight: 100 900;
font-display: swap;
}
Caching strategy
Cache-Control headers
# HTML (short or no cache)
Cache-Control: no-cache, must-revalidate
# Static assets with hash (immutable)
Cache-Control: public, max-age=31536000, immutable
# Static assets without hash
Cache-Control: public, max-age=86400, stale-while-revalidate=604800
# API responses
Cache-Control: private, max-age=0, must-revalidate
Service worker caching
// Cache-first for static assets
self.addEventListener('fetch', (event) => {
if (event.request.destination === 'image' ||
event.request.destination === 'style' ||
event.request.destination === 'script') {
event.respondWith(
caches.match(event.request).then((cached) => {
return cached || fetch(event.request).then((response) => {
const clone = response.clone();
caches.open('static-v1').then((cache) => cache.put(event.request, clone));
return response;
});
})
);
}
});
Runtime performance
Avoid layout thrashing
// ❌ Forces multiple reflows
elements.forEach(el => {
const height = el.offsetHeight; // Read
el.style.height = height + 10 + 'px'; // Write
});
// ✅ Batch reads, then batch writes
const heights = elements.map(el => el.offsetHeight); // All reads
elements.forEach((el, i) => {
el.style.height = heights[i] + 10 + 'px'; // All writes
});
Debounce expensive operations
function debounce(fn, delay) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}
// Debounce scroll/resize handlers
window.addEventListener('scroll', debounce(handleScroll, 100));
Use requestAnimationFrame
// ❌ May cause jank
setInterval(animate, 16);
// ✅ Synced with display refresh
function animate() {
// Animation logic
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
Virtualize long lists
// For lists > 100 items, render only visible items
// Use libraries like react-window, vue-virtual-scroller, or native CSS:
.virtual-list {
content-visibility: auto;
contain-intrinsic-size: 0 50px; /* Estimated item height */
}
Smooth navigations with View Transitions
The View Transitions API lets the browser cross-fade (or custom-animate) between two DOM states using a single GPU-composited snapshot — no double-render, no layout thrash, and the snapshot doesn't count toward CLS.
Same-document (SPA-style) — Baseline 2026:
// Wrap the DOM mutation that swaps the view
function navigate(newView) {
if (!document.startViewTransition) return swapDOM(newView);
document.startViewTransition(() => swapDOM(newView));
}
Cross-document (MPA-style) — Chromium-stable, progressive enhancement elsewhere:
/* On both source and destination pages */
@view-transition { navigation: auto; }
That's the entire integration — same-origin navigations now fade automatically. To opt specific elements into shared-element transitions (e.g. a thumbnail expanding into a hero), give them a matching view-transition-name:
.product-thumb[data-id="42"], .product-hero { view-transition-name: product-42; }
Pair this with Speculation Rules (above) for instant + animated navigations.
Third-party scripts
Load strategies
// ❌ Blocks main thread
<script src="https://analytics.example.com/script.js"></script>
// ✅ Async loading
<script async src="https://analytics.example.com/script.js"></script>
// ✅ Delay until interaction
<script>
document.addEventListener('DOMContentLoaded', () => {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
const script = document.createElement('script');
script.src = 'https://widget.example.com/embed.js';
document.body.appendChild(script);
observer.disconnect();
}
});
observer.observe(document.querySelector('#widget-container'));
});
</script>
Facade pattern
<!-- Show static placeholder until interaction -->
<div class="youtube-facade"
data-video-id="abc123"
onclick="loadYouTube(this)">
<img src="/thumbnails/abc123.jpg" alt="Video title">
<button aria-label="Play video">▶</button>
</div>
Measurement
Use the measurement workflow whenever a URL is runnable. It defines Chrome DevTools MCP routing, CrUX and fallback sources, repeatable lab conditions, and a compact evidence format.
| Metric | Kind | Interpretation |
|---|---|---|
| LCP, INP, CLS at p75 | Field | User-outcome Core Web Vitals; use for pass/fail prioritization |
| LCP, CLS in a trace | Lab | Reproducible diagnostic values for one navigation |
| TBT | Lab | Main-thread blocking diagnostic and a rough INP proxy, not field INP |
| FCP, Speed Index | Lab | Loading diagnostics, not Core Web Vitals |
Raw PerformanceObserver snippets are useful for the current browser session but are not real-user data by themselves. When the user wants production telemetry, read the first-party RUM reference and prefer web-vitals over a hand-rolled metric implementation.
References
For Core Web Vitals specific optimizations, see Core Web Vitals.
| 1 | |
| 2 | name performance |
| 3 | description Optimize web performance for faster loading and better user experience. Use when asked to "speed up my site", "optimize performance", "reduce load time", "fix slow loading", "improve page speed", or "performance audit". |
| 4 | license MIT |
| 5 | metadata |
| 6 | author web-quality-skills |
| 7 | version "2.0" |
| 8 | |
| 9 | |
| 10 | # Performance optimization |
| 11 | |
| 12 | Evidence-led performance optimization using real-user signals for prioritization and browser traces for diagnosis. Focuses on loading speed, runtime responsiveness, and resource delivery. |
| 13 | |
| 14 | ## How it works |
| 15 | |
| 16 | If a page can run, read [the measurement workflow] and establish a field-plus-lab baseline before editing. |
| 17 | Prioritize poor real-user Core Web Vitals. Use a DevTools performance trace and its focused insights to find the cause. |
| 18 | Inspect and change only the code or assets connected to measured bottlenecks. |
| 19 | Re-run equivalent lab measurements and report before/after values, conditions, and uncertainty. Field verification remains pending until enough new user data arrives. |
| 20 | |
| 21 | When no runnable page exists, perform static inspection but call findings **hypotheses**, not measured regressions. Include the command or browser workflow that can verify each high-impact hypothesis. |
| 22 | |
| 23 | Prefer a browser tool that records a performance trace and exposes focused insights. With Chrome DevTools MCP, use `performance_start_trace` and `performance_analyze_insight`; do not route performance through `lighthouse_audit`, which covers non-performance Lighthouse categories. |
| 24 | |
| 25 | ## Starting performance budget |
| 26 | |
| 27 | Budgets must reflect the product's target devices, networks, page types, and user journeys. The values below are initial guardrails for a typical content or commerce page, not universal pass/fail criteria. Preserve an existing project budget when one is already defined. |
| 28 | |
| 29 | | Resource | Budget | Rationale | |
| 30 | |----------|--------|-----------| |
| 31 | | Total page weight | < 1.5 MB | Bounds transfer time and data cost on constrained target networks; calibrate with representative pages | |
| 32 | | JavaScript (compressed) | < 300 KB | Protect parse and execution cost | |
| 33 | | CSS (compressed) | < 100 KB | Limit render-blocking work | |
| 34 | | Images (above-fold) | < 500 KB | Protect likely LCP resources | |
| 35 | | Fonts | < 100 KB | Limit critical font transfer | |
| 36 | | Third-party | < 200 KB | Bound code outside product control | |
| 37 | |
| 38 | ## Critical rendering path |
| 39 | |
| 40 | ### Server response |
| 41 | **TTFB < 800ms.** Time to First Byte should be fast. Use CDN, caching, and efficient backends. |
| 42 | **Enable compression.** Gzip or Brotli for text assets. Brotli preferred (15-20% smaller). |
| 43 | **HTTP/2 or HTTP/3.** Multiplexing reduces connection overhead. |
| 44 | **Edge caching.** Cache HTML at CDN edge when possible. |
| 45 | **Consider Early Hints (HTTP 103) for measured document latency.** If a trace shows slow HTML generation and stable critical subresources, send an interim `103` with `Link` headers before the normal final response from the same request. Use HTTP/2 or later. A CDN may synthesize the `103` from `Link` headers on an earlier `200`, or the origin/edge handler can emit it directly. Unsupported clients continue to the final response, but confirm current browser and infrastructure support. Limit hints to proven critical preloads or preconnects: inaccurate hints waste bandwidth. Cloudflare reported a 20–30% LCP improvement in an artificial, image-heavy test; treat that as a vendor case study, not an expected saving, and measure your result. See [MDN's 103 implementation example] and [the Cloudflare study]. |
| 46 | |
| 47 | ### Resource loading |
| 48 | |
| 49 | **Preconnect to required origins:** |
| 50 | |
| 51 | <link rel="preconnect" href="https://fonts.googleapis.com"> |
| 52 | <link rel="preconnect" href="https://cdn.example.com" crossorigin> |
| 53 | |
| 54 | |
| 55 | **Preload critical resources:** |
| 56 | |
| 57 | Preload only resources whose late discovery is visible in the trace. Each preload competes for bandwidth and an unnecessary high-priority request can delay LCP. |
| 58 | |
| 59 | |
| 60 | <!-- LCP image --> |
| 61 | <link rel="preload" href="/hero.webp" as="image" fetchpriority="high"> |
| 62 | |
| 63 | <!-- Critical font --> |
| 64 | <link rel="preload" href="/font.woff2" as="font" type="font/woff2" crossorigin> |
| 65 | |
| 66 | |
| 67 | **Prerender likely-next navigations** with the [Speculation Rules API]: |
| 68 | |
| 69 | <script type="speculationrules"> |
| 70 | { |
| 71 | "prerender": [{ |
| 72 | "where": { "href_matches": "/*" }, |
| 73 | "eagerness": "moderate" |
| 74 | }] |
| 75 | } |
| 76 | </script> |
| 77 | |
| 78 | `moderate` waits for a stronger intent signal than eager modes. Measure prediction hit rate, transferred bytes, and server cost; a wrong prerender is roughly an unused navigation. See [core-web-vitals → LCP] for the tradeoffs and the `prerenderingchange` gating needed for analytics. |
| 79 | |
| 80 | **Defer non-critical CSS:** |
| 81 | |
| 82 | <!-- Critical CSS inlined --> |
| 83 | <style>/* Above-fold styles */</style> |
| 84 | |
| 85 | <!-- Non-critical CSS --> |
| 86 | <link rel="preload" href="/styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'"> |
| 87 | <noscript><link rel="stylesheet" href="/styles.css"></noscript> |
| 88 | |
| 89 | |
| 90 | ### JavaScript optimization |
| 91 | |
| 92 | **Defer non-essential scripts:** |
| 93 | |
| 94 | <!-- Parser-blocking (avoid) --> |
| 95 | <script src="/critical.js"></script> |
| 96 | |
| 97 | <!-- Deferred (preferred) --> |
| 98 | <script defer src="/app.js"></script> |
| 99 | |
| 100 | <!-- Async (for independent scripts) --> |
| 101 | <script async src="/analytics.js"></script> |
| 102 | |
| 103 | <!-- Module (deferred by default) --> |
| 104 | <script type="module" src="/app.mjs"></script> |
| 105 | |
| 106 | |
| 107 | **Code splitting patterns:** |
| 108 | |
| 109 | // Route-based splitting |
| 110 | const Dashboard = lazy(() => import('./Dashboard')); |
| 111 | |
| 112 | // Component-based splitting |
| 113 | const HeavyChart = lazy(() => import('./HeavyChart')); |
| 114 | |
| 115 | // Feature-based splitting |
| 116 | if (user.isPremium) { |
| 117 | const PremiumFeatures = await import('./PremiumFeatures'); |
| 118 | } |
| 119 | |
| 120 | |
| 121 | **Tree shaking best practices:** |
| 122 | |
| 123 | // ❌ Imports entire library |
| 124 | import _ from 'lodash'; |
| 125 | _.debounce(fn, 300); |
| 126 | |
| 127 | // ✅ Imports only what's needed |
| 128 | import debounce from 'lodash/debounce'; |
| 129 | debounce(fn, 300); |
| 130 | |
| 131 | |
| 132 | ## Image optimization |
| 133 | |
| 134 | ### Format selection |
| 135 | | Format | Use case | Browser support | |
| 136 | |--------|----------|-----------------| |
| 137 | | AVIF | Photos, best compression | 92%+ | |
| 138 | | WebP | Photos, good fallback | 97%+ | |
| 139 | | PNG | Graphics with transparency | Universal | |
| 140 | | SVG | Icons, logos, illustrations | Universal | |
| 141 | |
| 142 | ### Responsive images |
| 143 | |
| 144 | <picture> |
| 145 | <!-- AVIF for modern browsers --> |
| 146 | <source |
| 147 | type="image/avif" |
| 148 | srcset="hero-400.avif 400w, |
| 149 | hero-800.avif 800w, |
| 150 | hero-1200.avif 1200w" |
| 151 | sizes="(max-width: 600px) 100vw, 50vw"> |
| 152 | |
| 153 | <!-- WebP fallback --> |
| 154 | <source |
| 155 | type="image/webp" |
| 156 | srcset="hero-400.webp 400w, |
| 157 | hero-800.webp 800w, |
| 158 | hero-1200.webp 1200w" |
| 159 | sizes="(max-width: 600px) 100vw, 50vw"> |
| 160 | |
| 161 | <!-- JPEG fallback --> |
| 162 | <img |
| 163 | src="hero-800.jpg" |
| 164 | srcset="hero-400.jpg 400w, |
| 165 | hero-800.jpg 800w, |
| 166 | hero-1200.jpg 1200w" |
| 167 | sizes="(max-width: 600px) 100vw, 50vw" |
| 168 | width="1200" |
| 169 | height="600" |
| 170 | alt="Hero image" |
| 171 | loading="lazy" |
| 172 | decoding="async"> |
| 173 | </picture> |
| 174 | |
| 175 | |
| 176 | ### LCP image priority |
| 177 | |
| 178 | <!-- Above-fold LCP image: eager loading, high priority --> |
| 179 | <img |
| 180 | src="hero.webp" |
| 181 | fetchpriority="high" |
| 182 | loading="eager" |
| 183 | decoding="sync" |
| 184 | alt="Hero"> |
| 185 | |
| 186 | <!-- Below-fold images: lazy loading --> |
| 187 | <img |
| 188 | src="product.webp" |
| 189 | loading="lazy" |
| 190 | decoding="async" |
| 191 | alt="Product"> |
| 192 | |
| 193 | |
| 194 | ## Font optimization |
| 195 | |
| 196 | ### Loading strategy |
| 197 | |
| 198 | /* System font stack as fallback */ |
| 199 | body { |
| 200 | font-family: 'Custom Font', -apple-system, BlinkMacSystemFont, |
| 201 | 'Segoe UI', Roboto, sans-serif; |
| 202 | } |
| 203 | |
| 204 | /* Prevent invisible text */ |
| 205 | @font-face { |
| 206 | font-family: 'Custom Font'; |
| 207 | src: url('/fonts/custom.woff2') format('woff2'); |
| 208 | font-display: swap; /* or optional for non-critical */ |
| 209 | font-weight: 400; |
| 210 | font-style: normal; |
| 211 | unicode-range: U+0000-00FF; /* Subset to Latin */ |
| 212 | } |
| 213 | |
| 214 | |
| 215 | ### Preloading critical fonts |
| 216 | |
| 217 | <link rel="preload" href="/fonts/heading.woff2" as="font" type="font/woff2" crossorigin> |
| 218 | |
| 219 | |
| 220 | ### Variable fonts |
| 221 | |
| 222 | /* One file instead of multiple weights */ |
| 223 | @font-face { |
| 224 | font-family: 'Inter'; |
| 225 | src: url('/fonts/Inter-Variable.woff2') format('woff2-variations'); |
| 226 | font-weight: 100 900; |
| 227 | font-display: swap; |
| 228 | } |
| 229 | |
| 230 | |
| 231 | ## Caching strategy |
| 232 | |
| 233 | ### Cache-Control headers |
| 234 | |
| 235 | # HTML (short or no cache) |
| 236 | Cache-Control: no-cache, must-revalidate |
| 237 | |
| 238 | # Static assets with hash (immutable) |
| 239 | Cache-Control: public, max-age=31536000, immutable |
| 240 | |
| 241 | # Static assets without hash |
| 242 | Cache-Control: public, max-age=86400, stale-while-revalidate=604800 |
| 243 | |
| 244 | # API responses |
| 245 | Cache-Control: private, max-age=0, must-revalidate |
| 246 | |
| 247 | |
| 248 | ### Service worker caching |
| 249 | |
| 250 | // Cache-first for static assets |
| 251 | self.addEventListener('fetch', (event) => { |
| 252 | if (event.request.destination === 'image' || |
| 253 | event.request.destination === 'style' || |
| 254 | event.request.destination === 'script') { |
| 255 | event.respondWith( |
| 256 | caches.match(event.request).then((cached) => { |
| 257 | return cached || fetch(event.request).then((response) => { |
| 258 | const clone = response.clone(); |
| 259 | caches.open('static-v1').then((cache) => cache.put(event.request, clone)); |
| 260 | return response; |
| 261 | }); |
| 262 | }) |
| 263 | ); |
| 264 | } |
| 265 | }); |
| 266 | |
| 267 | |
| 268 | ## Runtime performance |
| 269 | |
| 270 | ### Avoid layout thrashing |
| 271 | |
| 272 | // ❌ Forces multiple reflows |
| 273 | elements.forEach(el => { |
| 274 | const height = el.offsetHeight; // Read |
| 275 | el.style.height = height + 10 + 'px'; // Write |
| 276 | }); |
| 277 | |
| 278 | // ✅ Batch reads, then batch writes |
| 279 | const heights = elements.map(el => el.offsetHeight); // All reads |
| 280 | elements.forEach((el, i) => { |
| 281 | el.style.height = heights[i] + 10 + 'px'; // All writes |
| 282 | }); |
| 283 | |
| 284 | |
| 285 | ### Debounce expensive operations |
| 286 | |
| 287 | function debounce(fn, delay) { |
| 288 | let timeout; |
| 289 | return (...args) => { |
| 290 | clearTimeout(timeout); |
| 291 | timeout = setTimeout(() => fn(...args), delay); |
| 292 | }; |
| 293 | } |
| 294 | |
| 295 | // Debounce scroll/resize handlers |
| 296 | window.addEventListener('scroll', debounce(handleScroll, 100)); |
| 297 | |
| 298 | |
| 299 | ### Use requestAnimationFrame |
| 300 | |
| 301 | // ❌ May cause jank |
| 302 | setInterval(animate, 16); |
| 303 | |
| 304 | // ✅ Synced with display refresh |
| 305 | function animate() { |
| 306 | // Animation logic |
| 307 | requestAnimationFrame(animate); |
| 308 | } |
| 309 | requestAnimationFrame(animate); |
| 310 | |
| 311 | |
| 312 | ### Virtualize long lists |
| 313 | |
| 314 | // For lists > 100 items, render only visible items |
| 315 | // Use libraries like react-window, vue-virtual-scroller, or native CSS: |
| 316 | .virtual-list { |
| 317 | content-visibility: auto; |
| 318 | contain-intrinsic-size: 0 50px; /* Estimated item height */ |
| 319 | } |
| 320 | |
| 321 | |
| 322 | ### Smooth navigations with View Transitions |
| 323 | |
| 324 | The [View Transitions API] lets the browser cross-fade (or custom-animate) between two DOM states using a single GPU-composited snapshot — no double-render, no layout thrash, and the snapshot doesn't count toward CLS. |
| 325 | |
| 326 | **Same-document (SPA-style) — Baseline 2026:** |
| 327 | |
| 328 | // Wrap the DOM mutation that swaps the view |
| 329 | function navigate(newView) { |
| 330 | if (!document.startViewTransition) return swapDOM(newView); |
| 331 | document.startViewTransition(() => swapDOM(newView)); |
| 332 | } |
| 333 | |
| 334 | |
| 335 | **Cross-document (MPA-style) — Chromium-stable, progressive enhancement elsewhere:** |
| 336 | |
| 337 | /* On both source and destination pages */ |
| 338 | @view-transition { navigation: auto; } |
| 339 | |
| 340 | That's the entire integration — same-origin navigations now fade automatically. To opt specific elements into shared-element transitions (e.g. a thumbnail expanding into a hero), give them a matching `view-transition-name`: |
| 341 | |
| 342 | .product-thumb[data-id="42"], .product-hero { view-transition-name: product-42; } |
| 343 | |
| 344 | |
| 345 | Pair this with Speculation Rules (above) for instant + animated navigations. |
| 346 | |
| 347 | ## Third-party scripts |
| 348 | |
| 349 | ### Load strategies |
| 350 | |
| 351 | // ❌ Blocks main thread |
| 352 | <script src="https://analytics.example.com/script.js"></script> |
| 353 | |
| 354 | // ✅ Async loading |
| 355 | <script async src="https://analytics.example.com/script.js"></script> |
| 356 | |
| 357 | // ✅ Delay until interaction |
| 358 | <script> |
| 359 | document.addEventListener('DOMContentLoaded', () => { |
| 360 | const observer = new IntersectionObserver((entries) => { |
| 361 | if (entries[0].isIntersecting) { |
| 362 | const script = document.createElement('script'); |
| 363 | script.src = 'https://widget.example.com/embed.js'; |
| 364 | document.body.appendChild(script); |
| 365 | observer.disconnect(); |
| 366 | } |
| 367 | }); |
| 368 | observer.observe(document.querySelector('#widget-container')); |
| 369 | }); |
| 370 | </script> |
| 371 | |
| 372 | |
| 373 | ### Facade pattern |
| 374 | |
| 375 | <!-- Show static placeholder until interaction --> |
| 376 | <div class="youtube-facade" |
| 377 | data-video-id="abc123" |
| 378 | onclick="loadYouTube(this)"> |
| 379 | <img src="/thumbnails/abc123.jpg" alt="Video title"> |
| 380 | <button aria-label="Play video">▶</button> |
| 381 | </div> |
| 382 | |
| 383 | |
| 384 | ## Measurement |
| 385 | |
| 386 | Use [the measurement workflow] whenever a URL is runnable. It defines Chrome DevTools MCP routing, CrUX and fallback sources, repeatable lab conditions, and a compact evidence format. |
| 387 | |
| 388 | | Metric | Kind | Interpretation | |
| 389 | |--------|------|----------------| |
| 390 | | LCP, INP, CLS at p75 | Field | User-outcome Core Web Vitals; use for pass/fail prioritization | |
| 391 | | LCP, CLS in a trace | Lab | Reproducible diagnostic values for one navigation | |
| 392 | | TBT | Lab | Main-thread blocking diagnostic and a rough INP proxy, not field INP | |
| 393 | | FCP, Speed Index | Lab | Loading diagnostics, not Core Web Vitals | |
| 394 | |
| 395 | Raw `PerformanceObserver` snippets are useful for the current browser session but are not real-user data by themselves. When the user wants production telemetry, read [the first-party RUM reference] and prefer `web-vitals` over a hand-rolled metric implementation. |
| 396 | |
| 397 | ## References |
| 398 | |
| 399 | For Core Web Vitals specific optimizations, see [Core Web Vitals]. |
| 400 |
Discussion
Browse more free Claude skills or everything in Development.