0Pricing
Frontend Academy · Lesson

Service Worker Registration and Lifecycle

Register a Service Worker script, understand the install, activate, and fetch lifecycle events, and use skipWaiting and clients.claim.

Service Worker Registration and Lifecycle is a free Frontend Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is a Service Worker?

A Service Worker is a JavaScript file that runs in a separate browser worker (not the main thread) and intercepts network requests for your origin. It's the engine behind offline PWAs, push notifications, and background sync.

Registering a Service Worker

Register from your main script. Service workers require HTTPS (except on localhost).

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js', { scope: '/' })
      .then(reg => console.log('SW registered:', reg.scope))
      .catch(err => console.error('SW registration failed:', err));
  });
}

Scope

A service worker controls requests within its scope (the directory it's served from). /sw.js at the root controls everything. A SW at /app/sw.js only controls /app/*.

Lifecycle: install → activate → fetch

Three core events: install (one-time, set up caches), activate (one-time, clean up old caches), fetch (every request — decide cache vs network).

// sw.js
self.addEventListener('install', (event) => {
  console.log('SW installing');
  event.waitUntil(
    caches.open('v1').then(cache =>
      cache.addAll(['/', '/index.html', '/styles.css', '/app.js'])
    )
  );
});

self.addEventListener('activate', (event) => {
  console.log('SW active');
  event.waitUntil(
    caches.keys().then(keys =>
      Promise.all(keys.filter(k => k !== 'v1').map(k => caches.delete(k)))
    )
  );
});

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then(res => res || fetch(event.request))
  );
});

skipWaiting()

By default, an updated SW waits for all tabs to close before activating. self.skipWaiting() in the install handler forces immediate activation — faster updates but risks mixing old and new assets.

self.addEventListener('install', (event) => {
  self.skipWaiting(); // activate immediately on next reload
  // ... cache setup
});

clients.claim()

After activation, a new SW doesn't control pages that loaded before it. self.clients.claim() in the activate handler takes control immediately.

self.addEventListener('activate', (event) => {
  event.waitUntil(self.clients.claim());
});

Updating the Service Worker

Browsers check for a new sw.js on every navigation (24h max age). If the file content changed (byte-different), it installs as a new SW and waits to activate. Reload to trigger activation.

Detecting Updates from the App

Listen for updatefound to show an update prompt.

navigator.serviceWorker.register('/sw.js').then(reg => {
  reg.addEventListener('updatefound', () => {
    const newSW = reg.installing;
    newSW.addEventListener('statechange', () => {
      if (newSW.state === 'installed' && navigator.serviceWorker.controller) {
        // New version ready
        showUpdateBanner(() => {
          newSW.postMessage('SKIP_WAITING');
          window.location.reload();
        });
      }
    });
  });
});

Unregistering

To stop a runaway service worker (development gone wrong), unregister it.

navigator.serviceWorker.getRegistrations().then(regs => {
  for (const reg of regs) reg.unregister();
});

Browser DevTools

Chrome DevTools → Application → Service Workers shows registered SW, lets you unregister, simulate Update on reload, and step through lifecycle events.

Common Pitfalls

1) SW file must be at root scope or higher. 2) HTTPS required. 3) SW changes need a hard reload during development. 4) Cache once + update via versioning, not endless cache growth. 5) Don't cache POST requests (they're not supported).

Workbox — The Productivity Library

Google's Workbox abstracts the lifecycle and provides ready-made caching strategies. Most production PWAs use Workbox rather than hand-rolled SW code.

Quick Check

What does self.skipWaiting() do inside a service worker's install handler?

Recap: Service Worker Lifecycle

JavaScript worker intercepting network requests for your origin. Register via navigator.serviceWorker.register. Lifecycle: install (set up caches), activate (clean up), fetch (intercept requests). skipWaiting + clients.claim for immediate updates. Listen for updatefound to prompt users. Workbox abstracts the boilerplate. HTTPS required (except localhost).

Frequently asked questions

Is the “Service Worker Registration and Lifecycle” lesson free?

Yes — the full text of “Service Worker Registration and Lifecycle” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.

What will I learn in “Service Worker Registration and Lifecycle”?

Register a Service Worker script, understand the install, activate, and fetch lifecycle events, and use skipWaiting and clients.claim. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Frontend Academy?

No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Service Worker Registration and Lifecycle” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Frontend Academy lesson?

Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Web App Manifest
  2. Service Worker Registration and Lifecycle
  3. Offline Caching Strategies: CacheFirst NetworkFirst
  4. Push Notifications
← Back to Frontend Academy