âïž What Are Service Workers?
A Service Worker is a special type of JavaScript file that runs in the background, separate from the web page, and enables powerful features like:
â Offline caching
â Background sync
â Push notifications
â Intercepting and handling network requests
đ§ Think of it as a programmable network proxy between your app and the internet.
đ Key Capabilities
Feature | Description |
---|---|
đ Offline Support | Cache pages and assets so your site works without internet |
đ Network Interception | Serve cached files or fetch new ones intelligently |
đŹ Push Notifications | Re-engage users even when app is closed |
đ Background Sync | Retry failed requests once internet is back |
đ ïž Custom Fetch Handling | Decide how requests are handled (e.g., stale-while-revalidate) |
Â
đ Simple Example of a Service Worker
1. â
sw.js
(Service Worker Script)
js
const CACHE_NAME = 'v1';
const urlsToCache = ['/', '/index.html', '/styles.css', '/offline.html'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {
console.log('[Service Worker] Caching files');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
fetch(event.request).catch(() => caches.match(event.request).then(response => response || caches.match('/offline.html')))
);
});
2. â Register the Service Worker in Your App
js
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then(reg => console.log('Service Worker registered:', reg))
.catch(err => console.error('Service Worker failed:', err));
});
}
đ§ How It Works
Phase | Description |
---|---|
Install | Cache static files |
Activate | Clean up old caches |
Fetch | Intercept network requests & respond with cached data |
Push (optional) | Receive push notifications from a server |
Sync (optional) | Resume failed requests later |
Â
â ïž Service Worker Limitations
Must be served over HTTPS (except localhost)
Does not have access to DOM (use
postMessage
to communicate)Browser support is good but needs testing
Can be tricky to debug due to caching and versioning
đŠ Tools to Simplify Service Worker Use
Tool | Use Case |
---|---|
Workbox | Google’s library for building advanced SWs easily |
Create React App (CRA) | Comes with basic SW setup |
Next.js | Needs next-pwa plugin |
Vue CLI | Has a PWA plugin with SW support |
SvelteKit | Use vite-plugin-pwa for SWs |
Â
đ§Ș Test Your Service Worker
Use Chrome DevTools > Application tab > Service Workers
Simulate Offline Mode
Clear storage to force updates
Use Lighthouse to check PWA compliance