Lesson 3 / 29

Service Worker basics

Understand what service workers are and how to register them for offline functionality.

The essential idea

A service worker is a JavaScript file that runs in the background, separate from the main thread. It intercepts network requests, caches responses, and enables offline functionality—the core technology powering PWAs.

Register a service worker

This code registers a service worker file and handles registration success or failure.

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

Output:

Service Worker successfully registered and ready to intercept network requests.

Service Worker lifecycle

Service workers go through stages: parse, install, activate, and fetch events.

Service Worker lifecycle diagram showing registration, installation, activation, and message passing.
Figure 2.1 — Service Worker lifecycle and states.

A common trap

Service workers must be served over HTTPS (except localhost). This is a security requirement you cannot bypass.

Service worker registration patterns

Compare different registration strategies and error handling approaches.