Hint
Background JS proxy between app and network β enables offline support, push notifications, caching
A Service Worker is a script that runs in the background, separate from the page β acting as a network proxy. Enables progressive web app features.
// Registration (main thread)
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(reg => console.log('SW registered:', reg.scope))
.catch(err => console.error('SW failed:', err));
}
// sw.js β the service worker itself
const CACHE = 'v1';
const ASSETS = ['/index.html', '/styles.css', '/app.js'];
// Install β pre-cache core assets
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE).then(cache => cache.addAll(ASSETS))
);
});
// Activate β clean old caches
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys =>
Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
)
);
});
// Fetch β intercept ALL network requests
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(cached => {
return cached || fetch(event.request); // cache-first strategy
})
);
});
Capabilities: Offline caching, background sync, push notifications, intercepting requests, URL routing.