Service Worker
A service worker is a JavaScript file that runs in the background, separate from the web page. It acts as a programmable network proxy between the browser and the server.
Key characteristics
- Runs in a separate thread - no DOM access.
- Only works over HTTPS (or localhost).
- Persists across page loads - lives independently.
- Event-driven - activated by fetch, push, sync events.
Registration
ts
// main thread
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js')
.then(reg => console.log('SW registered:', reg.scope))
.catch(err => console.error('SW failed:', err));
}Lifecycle
text
install -> activate -> idle -> fetch/push/syncCaching strategies
ts
// sw.js
const CACHE = 'app-v1';
const PRECACHE = ['/index.html', '/app.css', '/app.js'];
// install - precache static assets
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE).then(cache => cache.addAll(PRECACHE))
);
});
// fetch - cache-first strategy
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then(cached => {
return cached ?? fetch(event.request).then(response => {
const clone = response.clone();
caches.open(CACHE).then(cache => cache.put(event.request, clone));
return response;
});
})
);
});Common caching strategies
| Strategy | How | Use for |
|---|---|---|
| Cache First | Cache -> network fallback | Static assets, fonts |
| Network First | Network -> cache fallback | API data, HTML |
| Stale While Revalidate | Cache immediately + update in background | Avatars, non-critical data |
| Cache Only | Cache only, no network | Offline-only content |
Other capabilities
ts
// Background Sync - retry failed requests when back online
self.addEventListener('sync', (event) => {
if (event.tag === 'send-message') {
event.waitUntil(sendPendingMessages());
}
});
// Push Notifications
self.addEventListener('push', (event) => {
const data = event.data.json();
event.waitUntil(
self.registration.showNotification(data.title, { body: data.body })
);
});Service workers are the backbone of Progressive Web Apps (PWA). Workbox by Google abstracts most of the low-level caching code into simple configuration.
updated
did you know it?