Concept
What is a Service Worker?
A Service Worker is a script that the browser runs in the background, completely separate from the main web page thread. Because it runs in a separate context, it:
- Has no direct access to the DOM (must communicate via
postMessage). - Runs on a separate thread, meaning it does not block user UI interactions.
- Is fully event-driven (it terminates when not in use, saving battery).
The Service Worker Lifecycle
A Service Worker moves through distinct lifecycle phases to ensure safe installation and background operation:
// In main client javascript thread:if ('serviceWorker' in navigator) {navigator.serviceWorker.register('/sw.js');}
The client browser checks for compatibility and registers the Service Worker file `/sw.js`. The browser downloads, parses, and executes the script in a background thread.
Network Interception
Once active, the Service Worker acts as a network proxy. Any resource request (CSS, JS, images, api queries) executes a 'fetch' event, letting the worker inspect and modify the response:
// sw.js - Intercept and log requests
self.addEventListener('fetch', (event) => {
console.log('Intercepting request:', event.request.url);
// event.respondWith allows returning cached assets
});Common Mistakes
1. Trying to access window, document, or localStorage inside a Service Worker
Service Workers run in worker threads, where browser DOM objects like window, document, and localStorage are unavailable. Accessing them throws runtime errors. Use self to access the worker scope and IndexedDB or the Cache API for storage.
2. Loading Service Workers over insecure HTTP connections
Service Workers can intercept all network traffic, making them high-security vectors. Browsers restrict Service Worker registration exclusively to secure origins (HTTPS) or localhost (for development).
Best Practices
- Check compatibility: Verify Service Worker support before calling registration scripts:
if ('serviceWorker' in navigator) { ... } - Skip Waiting cautiously: Use
self.skipWaiting()only if you need new service worker updates to force-activation immediately, bypassing the standard waiting tab lifecycle. - Implement Cache Cleaning: Utilize the
activateevent to delete old cache configurations when launching updates.
