3.5 Hours

9. Caching Strategies: Optimizing Asset Delivery

Caching

Caching is essential for fast load times. This module covers caching strategies for assets, including HTTP caching, service workers, and CDN caching. Understanding caching is essential for production performance.

The key insight is that caching reduces the number of requests and speeds up repeat visits. HTTP caching uses headers like Cache-Control and ETag. Service workers enable offline support. CDNs cache assets at the edge. This module covers all these strategies.

This module covers HTTP caching, service workers, CDN caching, and cache invalidation.

HTTP Caching

HTTP caching uses headers to control how browsers cache assets. Cache-Control defines caching behavior. ETag enables conditional requests. Last-Modified provides a timestamp for validation. Proper caching can reduce load times by 50-80%.

Common caching strategies: cache static assets indefinitely (with content hashes), cache HTML with revalidation, and cache API responses with TTL. Understanding HTTP caching is essential for performance.

Service Workers and Offline Support

Service workers enable offline support and advanced caching strategies. They intercept network requests and serve cached responses. Service workers can cache entire pages, assets, and API responses. They enable progressive web apps (PWAs) and offline experiences.

Implementing a service worker involves: registering the service worker, caching assets on install, intercepting requests, and updating the cache. Workbox simplifies service worker development.

JavaScript
// http caching headers (Nginx)
location /static/ {
  expires 1y;
  add_header Cache-Control "public, immutable";
}

location / {
  expires -1;
  add_header Cache-Control "no-cache, must-revalidate";
}

// Service worker with Workbox
// src/sw.js
import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { CacheFirst, StaleWhileRevalidate } from 'workbox-strategies';

// Precache static assets
precacheAndRoute(self.__WB_MANIFEST);

// Cache images with CacheFirst
registerRoute(
  /\.(?:png|gif|jpg|jpeg|svg|webp)$/,
  new CacheFirst({
    cacheName: 'images',
    plugins: [
      {
        cacheWillUpdate: ({ response }) => {
          return response.status === 200 ? response : null;
        },
      },
    ],
  })
);

// Cache API responses with StaleWhileRevalidate
registerRoute(
  /\/api\/.*/,
  new StaleWhileRevalidate({
    cacheName: 'api-cache',
  })
);

// Register service worker
// src/index.js
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js');
}

// CDN caching
// Cloudflare, CloudFront, etc. cache assets at the edge
// Use Cache-Control headers to control CDN caching

Try It Yourself: Implementing Caching

Follow these steps to implement caching strategies.

Step 1: Configure HTTP caching
Add Cache-Control headers for different asset types.

Step 2: Set up a service worker
npm install --save-dev workbox-webpack-plugin
Configure Workbox in your build tool.

Step 3: Implement cache invalidation
Use content hashes for asset filenames.

Step 4: Test caching
Check network requests in DevTools. Verify assets are cached.

Try It Yourself: Implement service worker for offline support. Test with Lighthouse. Configure CDN caching.

Knowledge Check

Ready to test your understanding of 9. Caching Strategies: Optimizing Asset Delivery?

Back