Service Worker Template
Scaffold an install/activate/fetch service worker.
Overview
The Service Worker Template scaffolds an sw.js file with the canonical lifecycle: install event precaches a list of assets, activate event cleans up old caches, fetch event serves cached responses with a configurable strategy (cache-first, network-first, stale-while-revalidate). Output is a complete, registration-ready service worker plus a snippet for navigator.serviceWorker.register.
Useful for front-end developers learning how to write a service worker for offline support or how to implement stale-while-revalidate in a service worker. Reach for it adding PWA capability to a site, building an offline fallback page, or accelerating repeat visits with a cache layer.
How it works
Service Workers are JavaScript files registered with the browser to intercept network requests originating from pages they control. They run in a separate worker thread with no DOM access. The lifecycle has three main events: install (precache critical assets), activate (purge old cache versions), and fetch (decide how each request is served).
Three common fetch strategies cover most use cases. Cache-first prioritises offline speed for static assets. Network-first prioritises freshness for HTML. Stale-while-revalidate returns the cached copy immediately while updating the cache in the background — the sweet spot for many resources.
Examples
- A PWA shell precaches
index.html,app.css,app.js, falls back to cache for navigation requests. - A documentation site uses stale-while-revalidate so visits feel instant but content stays current.
- An offline fallback page renders a friendly message when the network is unavailable and the requested resource is not cached.
- A version bump in
CACHE_NAMEtriggersactivatecleanup that removes the previous cache by name.
FAQ
Why does my new service worker not take effect?
Browsers wait until all pages controlled by the old worker close before activating the new one. Call self.skipWaiting() in install and clients.claim() in activate to force the transition.
Should I cache POST requests?
Generally no — the Cache API only supports GET. Use IndexedDB for mutation queues with background sync if you need offline POST handling.
Cache-first or stale-while-revalidate for HTML?
Stale-while-revalidate for sites that update frequently — users see something instantly and get fresh content on the next visit. Network-first for sites where staleness is unacceptable.
Why is my service worker restarting?
The browser unloads idle service workers aggressively. State must be persisted in the Cache API or IndexedDB, not in module-level variables.