Service Workers run in a separate thread from the page, intercepting network requests — the foundation that makes offline-capable Progressive Web Apps possible at all.
const CACHE_NAME = 'app-v1';
const urlsToCache = ['/', '/styles.css', '/app.js'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(urlsToCache))
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((cached) => cached || fetch(event.request))
);
});
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
This “cache-first” strategy above serves cached assets instantly and falls back to the network only when needed — combined with a web app manifest for installability, this is the actual mechanism behind a PWA working offline and appearing as an installable app icon on a phone’s home screen.