Service Worker
JavaScript script running in the browser background, enabling caching, push notifications, and offline functionality for web applications.
Updated on January 26, 2026
A Service Worker is a JavaScript script that runs independently of the web page, acting as a programmable proxy between the application and the network. This technology forms the foundation of Progressive Web Apps (PWA) by enabling advanced features like offline functionality, background sync, and push notifications. Unlike traditional scripts, the Service Worker persists even when the page is closed.
Fundamentals
- Separate thread running in background, with no direct DOM access
- Independent lifecycle (installation, activation, event listening)
- Network request interception via Fetch API
- Mandatory HTTPS requirement in production for security reasons
Benefits
- Offline user experience: content access without internet connection
- Enhanced performance: instant loading via local cache
- User engagement: push notifications even when app is closed
- Background synchronization: deferred data transmission
- Bandwidth savings: reduction of redundant network requests
Practical Example
Here's a basic Service Worker implementation with "Cache First" strategy:
// Service Worker registration
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(reg => console.log('SW registered', reg))
.catch(err => console.error('SW error', err));
}
// Service Worker file (sw.js)
const CACHE_NAME = 'app-v1';
const urlsToCache = [
'/',
'/styles/main.css',
'/script/app.js',
'/images/logo.png'
];
// Install
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(urlsToCache))
);
});
// Fetch interception
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
// Cache hit - return response
if (response) return response;
// Otherwise fetch and cache
return fetch(event.request).then(response => {
if (!response || response.status !== 200) {
return response;
}
const responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(cache => {
cache.put(event.request, responseToCache);
});
return response;
});
})
);
});
// Activation and cleanup
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
})
);
});Implementation
- Create Service Worker file at domain root (maximum scope)
- Register Service Worker from main application script
- Define appropriate caching strategy (Cache First, Network First, Stale While Revalidate)
- Implement complete lifecycle (install, fetch, activate)
- Manage versions and cache updates
- Test offline behavior with Chrome DevTools (Application tab)
- Implement skip waiting mechanism for critical updates
Pro Tip
Use Workbox, Google's library, to simplify Service Worker management. It provides preconfigured caching strategies, simplified routing, and automatically handles complex cases. In production, favor a hybrid strategy: Cache First for static assets, Network First for APIs, and Stale While Revalidate for images.
Related Tools
- Workbox: Google library to simplify Service Worker creation
- Chrome DevTools: debugging and inspection (Application > Service Workers)
- Lighthouse: PWA auditing and Service Worker verification
- sw-precache / sw-toolbox: legacy Google libraries
- Service Worker Precache Webpack Plugin: automatic cache generation
- IndexedDB: local storage for complex data accessible to Service Worker
Service Workers transform web applications into native-like experiences, delivering performance and resilience. For businesses, this technology reduces bandwidth costs, improves user retention, and maintains minimal service even during network failures. Investing in a PWA architecture based on Service Workers guarantees significant competitive advantage in markets with limited connectivity.
