Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Service Workers

Service Worker Basics

Understand what a service worker is, what it can and cannot do, how it differs from web workers, and how the event-driven model lets it power offline PWAs.

A service worker is the engine of a PWA. It is a JavaScript file that the browser runs in a separate thread, outside any web page. It can sit between your pages and the network, answer requests from a cache, receive push messages when your site is closed, and run background tasks. Everything that makes a PWA reliable depends on it.

Service workers are different from regular scripts in important ways: they have a lifecycle of their own, they cannot touch the DOM, they stop and restart whenever the browser wants, and one worker can control many pages at once. Misunderstanding these facts causes most service worker bugs. This lesson builds the mental model; the next ones go through registration, events and updates.

What a service worker is

Think of a service worker as a programmable network proxy that lives in the browser. When a page that the worker controls requests a file, the browser fires a fetch event in the worker, and the worker chooses the answer: from a cache, from the network, from a generated response, or an error.

flowchart LR
  P["Page (window)"] -->|"fetch / navigation"| S["Service worker"]
  S -->|"respondWith(...)"| P
  S --> C["Cache API"]
  S --> N["Network"]

The worker intercepts requests from the pages it controls. The page does not know it is there.

What it can and cannot do

Can Cannot
Intercept fetch requests of controlled pages Access the DOM or window
Use the Cache API and IndexedDB Use localStorage or sessionStorage
Receive push messages and show notifications Run forever (the browser stops idle workers)
Handle background sync events Keep global variables between runs
Talk to pages with postMessage Use synchronous XHR
Run on any page in its scope Run on insecure origins (except localhost)

The "cannot keep state" row is the surprise. A service worker is event driven and short lived: the browser starts it when an event arrives and stops it after a few seconds of idleness. Variables you set in the global scope are lost when it stops. Persistent information must go into the Cache API or IndexedDB.

The global scope: self

Inside a service worker, the global object is self (an instance of ServiceWorkerGlobalScope). There is no window. Frequently used members:

  • self.addEventListener(type, handler) to listen for events.
  • self.caches for the Cache API (also available as plain caches).
  • self.clients to find and message the pages it controls.
  • self.registration to access notifications, sync and the registration itself.
  • self.skipWaiting() to activate a waiting worker immediately.
  • fetch() and Response, Request, Headers, the same objects as in the page.
JavaScript
// sw.js
console.log('I run in', self.constructor.name);
// -> ServiceWorkerGlobalScope

self.addEventListener('install', (event) => { /* ... */ });
self.addEventListener('activate', (event) => { /* ... */ });
self.addEventListener('fetch', (event) => { /* ... */ });
self.addEventListener('message', (event) => { /* ... */ });
self.addEventListener('push', (event) => { /* ... */ });
self.addEventListener('sync', (event) => { /* ... */ });

Service workers vs. web workers

Both run off the main thread, but their purposes differ:

Web worker Service worker
Tied to One page An origin and scope, many pages
Lives While the page lives Independently, started and stopped by the browser
Intercepts network No Yes
Typical use Heavy computation Offline, push, background work
Created by new Worker(url) navigator.serviceWorker.register(url)

A page can use both.

Everything is asynchronous and promise based

Service worker APIs return promises. Because the worker may be stopped at any moment, you must tell the browser when asynchronous work is still in progress, using event.waitUntil(promise). Without it, the browser may stop the worker in the middle of your caching.

JavaScript
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('v1').then((cache) => cache.add('/offline.html'))
  );
});

The same idea applies to fetch with event.respondWith(promise): you hand the browser a promise for the response. Both are the heart of the programming model.

The one-sentence lifecycle

A new worker is registered, then installs, then waits if an older worker is still controlling pages, then activates, and then controls pages and receives fetch events. The next two lessons walk through each phase and the update process. For now, remember: installing and activating are separate steps, and a page is only controlled by a worker after it activates and the page is loaded or claimed.

A runnable model of the event-driven worker

Service workers cannot run in this page's sandbox, but their programming model can be shown with a tiny stand-in: a worker object holds event handlers, an "idle timer" stops it, and global state vanishes on restart. This clarifies why you must not store data in globals.

JS Stand-in: a worker that gets stopped

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The third line shows the lesson: after the stop, the counter began again at 1. If you need a counter or a queue that survives, write it to IndexedDB or a cache.

What a request interception looks like

The following stand-in imitates the page-worker-network triangle. A "page" calls pageFetch, the "browser" routes the request to the worker if one controls the page, and the worker decides. It uses real Response objects, which exist in browsers and Node.

JS Stand-in: a page, a worker and the network

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Debugging mindset

Because the worker is separate from the page, debugging differs:

  • Worker console.log output appears in the worker's own DevTools context. In Chrome use Application > Service workers and click the worker link, or select the worker in the Console's context dropdown.
  • Errors during install keep the old worker active, so a broken new version doesn't take the app down, but your changes also never apply. Always check the status shown in DevTools.
  • chrome://serviceworker-internals (or edge://serviceworker-internals) lists every registered worker in the browser.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which object is the global scope inside a service worker?

    Service workers have no window; self refers to the ServiceWorkerGlobalScope.
  2. 2. Why shouldn't you keep important data in a global variable of a service worker?

    Workers are event driven and short lived; persistent data belongs in IndexedDB or the Cache API.
  3. 3. What is event.waitUntil() for?

    waitUntil extends the event's lifetime until the promise settles.
  4. 4. What is a key difference from a web worker?

    Intercepting requests is the unique capability of service workers.

Summary

  • A service worker is an event-driven, background script acting as a programmable proxy for its scope.
  • It has no DOM and no localStorage; use the Cache API and IndexedDB.
  • The browser starts and stops it as needed, so globals do not persist.
  • event.waitUntil and event.respondWith keep asynchronous work alive.
  • Lifecycle: register, install, wait, activate, control.

Next: Registering a Service Worker