Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
👋 Hi! I'm Dastan, author of Hack Frontend. Always open to professional networking => connect with me on LinkedIn.
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:
Service Workers are used for:
install) — service worker loads and prepares cache.activate) — old data is cleaned, new cache is created.fetch) — intercepting and processing all requests, cache management.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));
});
}
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);
})
);
});
localhost in dev mode).window, document, localStorage.Open DevTools → Application → Service Workers There you can:
Service Worker is key element of Progressive Web App:
Important:
Service Workers are powerful but potentially dangerous tool. Always ensure correct update strategy to avoid caching outdated data!