Service Workers power offline experiences, push notifications, and background sync. At Google, every PWA starts with a solid Service Worker strategy.
Lifecycle
- Register: Browser downloads the SW script
- Install: Pre-cache critical assets
- Activate: Clean up old caches, take control
- Fetch: Intercept network requests
Caching Strategies
Cache First (Offline First)
Check cache first, fall back to network. Best for static assets.
Network First
Try network first, fall back to cache. Best for API calls where freshness matters.
Stale While Revalidate
Serve from cache immediately, update cache in background. Best balance of speed and freshness.
Common Pitfalls
- Cache Invalidation: Version your caches and delete old ones in the activate event
- Scope: SWs only control pages at or below their scope path
- Updates: A single byte change in sw.js triggers a new install, but the old SW stays active until all tabs close
- Navigation Preload: Use it to avoid the SW startup delay on navigation requests