Skip to main content

Performance Optimization

Deep performance optimization based on Lighthouse performance audits. Focuses on loading speed, runtime efficiency, and resource optimization.

How it Works

  1. Identify performance bottlenecks in code and assets
  2. Prioritize by impact on Core Web Vitals
  3. Provide specific optimizations with code examples
  4. Measure improvement with before/after metrics

Performance Budget

| Resource | Budget | Rationale | |----------|--------|-----------|| | Total page weight | < 1.5 MB | 3G loads in ~4s | | JavaScript (compressed) | < 300 KB | Parsing + execution time | | CSS (compressed) | < 100 KB | Render blocking | | Images (above-fold) | < 500 KB | LCP impact | | Fonts | < 100 KB | FOIT/FOUT prevention | | Third-party | < 200 KB | Uncontrolled latency |

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.

Resource Loading

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://cdn.example.com" crossorigin>

JavaScript Optimization

<!-- 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>

Image Optimization

Format Selection

FormatUse CaseBrowser Support
AVIFPhotos, best compression92%+
WebPPhotos, good fallback97%+
PNGGraphics with transparencyUniversal
SVGIcons, logos, illustrationsUniversal

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">

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 */
}

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

elements.forEach(el => {
  const height = el.offsetHeight; // Read
  el.style.height = height + 10 + 'px'; // Write
});

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

setInterval(animate, 16);

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 */
}

Third-Party Scripts

Load Strategies

<script src="https://analytics.example.com/script.js"></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

Key Metrics

MetricTargetTool
LCP< 2.5sLighthouse, CrUX
FCP< 1.8sLighthouse
Speed Index< 3.4sLighthouse
TBT< 200msLighthouse
TTI< 3.8sLighthouse

Testing Commands

# Lighthouse CLI
npx lighthouse https://example.com --output html --output-path report.html

# Web Vitals library
import {onLCP, onINP, onCLS} from 'web-vitals';
onLCP(console.log);
onINP(console.log);
onCLS(console.log);
For Core Web Vitals specific optimizations, see Core Web Vitals.

Build docs developers (and LLMs) love