Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Optimize web performance using Core Web Vitals, Lighthouse audits, and resource budgets.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
SKILL.md
1---2name: performance3description: 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".4license: MIT5metadata:6author: web-quality-skills7version: "1.0"8---910# Performance optimization1112Deep performance optimization based on Lighthouse performance audits. Focuses on loading speed, runtime efficiency, and resource optimization.1314## How it works15161. Identify performance bottlenecks in code and assets172. Prioritize by impact on Core Web Vitals183. Provide specific optimizations with code examples194. Measure improvement with before/after metrics2021## Performance budget2223| Resource | Budget | Rationale |24|----------|--------|-----------|25| Total page weight | < 1.5 MB | 3G loads in ~4s |26| JavaScript (compressed) | < 300 KB | Parsing + execution time |27| CSS (compressed) | < 100 KB | Render blocking |28| Images (above-fold) | < 500 KB | LCP impact |29| Fonts | < 100 KB | FOIT/FOUT prevention |30| Third-party | < 200 KB | Uncontrolled latency |3132## Critical rendering path3334### Server response35* **TTFB < 800ms.** Time to First Byte should be fast. Use CDN, caching, and efficient backends.36* **Enable compression.** Gzip or Brotli for text assets. Brotli preferred (15-20% smaller).37* **HTTP/2 or HTTP/3.** Multiplexing reduces connection overhead.38* **Edge caching.** Cache HTML at CDN edge when possible.39* **Send Early Hints (HTTP 103) for slow origins.** When the origin needs hundreds of milliseconds to assemble the final response, return a `103 Early Hints` with `Link: </hero.webp>; rel=preload; as=image` (and similar for critical CSS/fonts) so the browser starts fetching before the `200 OK` lands. Cloudflare reports [20–30% LCP improvements](https://blog.cloudflare.com/early-hints-performance/) on image-heavy pages. Requires HTTP/2+ and is supported by Chromium-based browsers; other browsers ignore the 103 and fall through to the 200 — safe to enable. CDNs (Cloudflare, Fastly, Akamai) can synthesize 103s automatically from prior responses; on your own origin, emit them from the same handler that issues the 200.4041### Resource loading4243**Preconnect to required origins:**44```html45<link rel="preconnect" href="https://fonts.googleapis.com">46<link rel="preconnect" href="https://cdn.example.com" crossorigin>47```4849**Preload critical resources:**50```html51<!-- LCP image -->52<link rel="preload" href="/hero.webp" as="image" fetchpriority="high">5354<!-- Critical font -->55<link rel="preload" href="/font.woff2" as="font" type="font/woff2" crossorigin>56```5758**Prerender likely-next navigations** with the [Speculation Rules API](https://developer.chrome.com/docs/web-platform/prerender-pages):59```html60<script type="speculationrules">61{62"prerender": [{63"where": { "href_matches": "/*" },64"eagerness": "moderate"65}]66}67</script>68```69`moderate` triggers after a ~200ms hover — usually intent-correlated, rarely wasted. See [core-web-vitals → LCP](../core-web-vitals/SKILL.md#lcp-largest-contentful-paint) for the full discussion of eagerness tradeoffs and the `prerenderingchange` gating you'll need for analytics.7071**Defer non-critical CSS:**72```html73<!-- Critical CSS inlined -->74<style>/* Above-fold styles */</style>7576<!-- Non-critical CSS -->77<link rel="preload" href="/styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">78<noscript><link rel="stylesheet" href="/styles.css"></noscript>79```8081### JavaScript optimization8283**Defer non-essential scripts:**84```html85<!-- Parser-blocking (avoid) -->86<script src="/critical.js"></script>8788<!-- Deferred (preferred) -->89<script defer src="/app.js"></script>9091<!-- Async (for independent scripts) -->92<script async src="/analytics.js"></script>9394<!-- Module (deferred by default) -->95<script type="module" src="/app.mjs"></script>96```9798**Code splitting patterns:**99```javascript100// Route-based splitting101const Dashboard = lazy(() => import('./Dashboard'));102103// Component-based splitting104const HeavyChart = lazy(() => import('./HeavyChart'));105106// Feature-based splitting107if (user.isPremium) {108const PremiumFeatures = await import('./PremiumFeatures');109}110```111112**Tree shaking best practices:**113```javascript114// ❌ Imports entire library115import _ from 'lodash';116_.debounce(fn, 300);117118// ✅ Imports only what's needed119import debounce from 'lodash/debounce';120debounce(fn, 300);121```122123## Image optimization124125### Format selection126| Format | Use case | Browser support |127|--------|----------|-----------------|128| AVIF | Photos, best compression | 92%+ |129| WebP | Photos, good fallback | 97%+ |130| PNG | Graphics with transparency | Universal |131| SVG | Icons, logos, illustrations | Universal |132133### Responsive images134```html135<picture>136<!-- AVIF for modern browsers -->137<source138type="image/avif"139srcset="hero-400.avif 400w,140hero-800.avif 800w,141hero-1200.avif 1200w"142sizes="(max-width: 600px) 100vw, 50vw">143144<!-- WebP fallback -->145<source146type="image/webp"147srcset="hero-400.webp 400w,148hero-800.webp 800w,149hero-1200.webp 1200w"150sizes="(max-width: 600px) 100vw, 50vw">151152<!-- JPEG fallback -->153<img154src="hero-800.jpg"155srcset="hero-400.jpg 400w,156hero-800.jpg 800w,157hero-1200.jpg 1200w"158sizes="(max-width: 600px) 100vw, 50vw"159width="1200"160height="600"161alt="Hero image"162loading="lazy"163decoding="async">164</picture>165```166167### LCP image priority168```html169<!-- Above-fold LCP image: eager loading, high priority -->170<img171src="hero.webp"172fetchpriority="high"173loading="eager"174decoding="sync"175alt="Hero">176177<!-- Below-fold images: lazy loading -->178<img179src="product.webp"180loading="lazy"181decoding="async"182alt="Product">183```184185## Font optimization186187### Loading strategy188```css189/* System font stack as fallback */190body {191font-family: 'Custom Font', -apple-system, BlinkMacSystemFont,192'Segoe UI', Roboto, sans-serif;193}194195/* Prevent invisible text */196@font-face {197font-family: 'Custom Font';198src: url('/fonts/custom.woff2') format('woff2');199font-display: swap; /* or optional for non-critical */200font-weight: 400;201font-style: normal;202unicode-range: U+0000-00FF; /* Subset to Latin */203}204```205206### Preloading critical fonts207```html208<link rel="preload" href="/fonts/heading.woff2" as="font" type="font/woff2" crossorigin>209```210211### Variable fonts212```css213/* One file instead of multiple weights */214@font-face {215font-family: 'Inter';216src: url('/fonts/Inter-Variable.woff2') format('woff2-variations');217font-weight: 100 900;218font-display: swap;219}220```221222## Caching strategy223224### Cache-Control headers225```226# HTML (short or no cache)227Cache-Control: no-cache, must-revalidate228229# Static assets with hash (immutable)230Cache-Control: public, max-age=31536000, immutable231232# Static assets without hash233Cache-Control: public, max-age=86400, stale-while-revalidate=604800234235# API responses236Cache-Control: private, max-age=0, must-revalidate237```238239### Service worker caching240```javascript241// Cache-first for static assets242self.addEventListener('fetch', (event) => {243if (event.request.destination === 'image' ||244event.request.destination === 'style' ||245event.request.destination === 'script') {246event.respondWith(247caches.match(event.request).then((cached) => {248return cached || fetch(event.request).then((response) => {249const clone = response.clone();250caches.open('static-v1').then((cache) => cache.put(event.request, clone));251return response;252});253})254);255}256});257```258259## Runtime performance260261### Avoid layout thrashing262```javascript263// ❌ Forces multiple reflows264elements.forEach(el => {265const height = el.offsetHeight; // Read266el.style.height = height + 10 + 'px'; // Write267});268269// ✅ Batch reads, then batch writes270const heights = elements.map(el => el.offsetHeight); // All reads271elements.forEach((el, i) => {272el.style.height = heights[i] + 10 + 'px'; // All writes273});274```275276### Debounce expensive operations277```javascript278function debounce(fn, delay) {279let timeout;280return (...args) => {281clearTimeout(timeout);282timeout = setTimeout(() => fn(...args), delay);283};284}285286// Debounce scroll/resize handlers287window.addEventListener('scroll', debounce(handleScroll, 100));288```289290### Use requestAnimationFrame291```javascript292// ❌ May cause jank293setInterval(animate, 16);294295// ✅ Synced with display refresh296function animate() {297// Animation logic298requestAnimationFrame(animate);299}300requestAnimationFrame(animate);301```302303### Virtualize long lists304```javascript305// For lists > 100 items, render only visible items306// Use libraries like react-window, vue-virtual-scroller, or native CSS:307.virtual-list {308content-visibility: auto;309contain-intrinsic-size: 0 50px; /* Estimated item height */310}311```312313### Smooth navigations with View Transitions314315The [View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions) 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.316317**Same-document (SPA-style) — Baseline 2026:**318```javascript319// Wrap the DOM mutation that swaps the view320function navigate(newView) {321if (!document.startViewTransition) return swapDOM(newView);322document.startViewTransition(() => swapDOM(newView));323}324```325326**Cross-document (MPA-style) — Chromium-stable, progressive enhancement elsewhere:**327```css328/* On both source and destination pages */329@view-transition { navigation: auto; }330```331That'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`:332```css333.product-thumb[data-id="42"], .product-hero { view-transition-name: product-42; }334```335336Pair this with Speculation Rules (above) for instant + animated navigations.337338## Third-party scripts339340### Load strategies341```javascript342// ❌ Blocks main thread343<script src="https://analytics.example.com/script.js"></script>344345// ✅ Async loading346<script async src="https://analytics.example.com/script.js"></script>347348// ✅ Delay until interaction349<script>350document.addEventListener('DOMContentLoaded', () => {351const observer = new IntersectionObserver((entries) => {352if (entries[0].isIntersecting) {353const script = document.createElement('script');354script.src = 'https://widget.example.com/embed.js';355document.body.appendChild(script);356observer.disconnect();357}358});359observer.observe(document.querySelector('#widget-container'));360});361</script>362```363364### Facade pattern365```html366<!-- Show static placeholder until interaction -->367<div class="youtube-facade"368data-video-id="abc123"369onclick="loadYouTube(this)">370<img src="/thumbnails/abc123.jpg" alt="Video title">371<button aria-label="Play video">▶</button>372</div>373```374375## Measurement376377### Key metrics378| Metric | Target | Tool |379|--------|--------|------|380| LCP | < 2.5s | Lighthouse, CrUX |381| FCP | < 1.8s | Lighthouse |382| Speed Index | < 3.4s | Lighthouse |383| TBT | < 200ms | Lighthouse |384| TTI | < 3.8s | Lighthouse |385386### Testing commands387```bash388# Lighthouse CLI389npx lighthouse https://example.com --output html --output-path report.html390391# Web Vitals library392import {onLCP, onINP, onCLS} from 'web-vitals';393onLCP(console.log);394onINP(console.log);395onCLS(console.log);396```397398## References399400For Core Web Vitals specific optimizations, see [Core Web Vitals](../core-web-vitals/SKILL.md).401