What is Service Worker?
Service Worker is background script that works separately from browser's main thread, intercepts network requests, manages caching and provides offline web application work.
It has no access to DOM, but can:
- cache resources,
- process network requests,
- show push notifications,
- perform background data synchronization.
Why is it Needed?
Service Workers are used for:
- Offline access (Progressive Web Apps)
- Faster loading via cache
- Push notification handling
- Background data synchronization
- Server behavior simulation (Mock API)
Lifecycle
- Installation (
install) — service worker loads and prepares cache. - Activation (
activate) — old data is cleaned, new cache is created. - Work (
fetch) — intercepting and processing all requests, cache management. - Deletion — when not used, deleted from browser.
Service Worker Registration Example
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then(reg => console.log('SW registered:', reg))
.catch(err => console.error('SW error:', err));
});
}
sw.js File Example
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('v1').then((cache) => {
return cache.addAll(['/index.html', '/styles.css', '/script.js']);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((cached) => {
return cached || fetch(event.request);
})
);
});
Limitations
- Work only over HTTPS (or
localhostin dev mode). - No access to
window,document,localStorage. - Not supported in old browsers.
How to Check?
Open DevTools → Application → Service Workers There you can:
- Reregister SW.
- Stop SW.
- Delete SW.
Usage with PWA
Service Worker is key element of Progressive Web App:
- Manages offline mode
- Caches and updates resources
- Provides instant loading and background synchronization
Important:
Service Workers are powerful but potentially dangerous tool. Always ensure correct update strategy to avoid caching outdated data!