Network and Delivery OptimizationLesson 5.5
How to implement a service worker for offline caching and faster repeat visits
service worker lifecycle, install event, fetch event, cache-first strategy, network-first strategy, stale-while-revalidate, Workbox, background sync, service worker scope
Service Workers for Caching
A service worker is a JavaScript file that runs in a background thread and intercepts all network requests from your page. It acts as a programmable proxy โ you decide per-URL whether to serve from cache, network, or a combination.
// service-worker.js โ cache-first strategy for static assets
const CACHE_NAME = 'v1';
const ASSETS = ['/index.html', '/styles.css', '/app.js'];
self.addEventListener('install', e => {
e.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS))
);
});
self.addEventListener('fetch', e => {
e.respondWith(
caches.match(e.request).then(cached => {
return cached || fetch(e.request).then(res => {
const clone = res.clone();
caches.open(CACHE_NAME).then(c => c.put(e.request, clone));
return res;
});
})
);
});Use Workbox (Google's service worker library) to avoid writing cache logic manually:
import { registerRoute } from 'workbox-routing';
import { CacheFirst, NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies';
// Images: cache-first, 30-day expiry
registerRoute(({ request }) => request.destination === 'image',
new CacheFirst({ cacheName: 'images', plugins: [new ExpirationPlugin({ maxAgeSeconds: 2592000 })] })
);
// API: network-first with cache fallback
registerRoute(({ url }) => url.pathname.startsWith('/api/'),
new NetworkFirst()
);Register the service worker from your main JS file:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}