Skip to content
web technology questions

Web Technology · 10 of 10senior~2 min

What is a Service Worker and what can it do?

#pwa#browser#performance#offline

Service Worker

A service worker is a JavaScript file that runs in the background, separate from the web page. It acts as a programmable network proxy between the browser and the server.

Key characteristics

  • Runs in a separate thread - no DOM access.
  • Only works over HTTPS (or localhost).
  • Persists across page loads - lives independently.
  • Event-driven - activated by fetch, push, sync events.

Registration

ts
// 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)); }

Lifecycle

text
install -> activate -> idle -> fetch/push/sync

Caching strategies

ts
// sw.js const CACHE = 'app-v1'; const PRECACHE = ['/index.html', '/app.css', '/app.js']; // install - precache static assets self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE).then(cache => cache.addAll(PRECACHE)) ); }); // fetch - cache-first strategy self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then(cached => { return cached ?? fetch(event.request).then(response => { const clone = response.clone(); caches.open(CACHE).then(cache => cache.put(event.request, clone)); return response; }); }) ); });

Common caching strategies

StrategyHowUse for
Cache FirstCache -> network fallbackStatic assets, fonts
Network FirstNetwork -> cache fallbackAPI data, HTML
Stale While RevalidateCache immediately + update in backgroundAvatars, non-critical data
Cache OnlyCache only, no networkOffline-only content

Other capabilities

ts
// Background Sync - retry failed requests when back online self.addEventListener('sync', (event) => { if (event.tag === 'send-message') { event.waitUntil(sendPendingMessages()); } }); // Push Notifications self.addEventListener('push', (event) => { const data = event.data.json(); event.waitUntil( self.registration.showNotification(data.title, { body: data.body }) ); });

Service workers are the backbone of Progressive Web Apps (PWA). Workbox by Google abstracts most of the low-level caching code into simple configuration.

updated

did you know it?

related questions