Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Service Workers

Registering a Service Worker

Learn how to register a service worker correctly: feature detection, load timing, scope rules, the Service-Worker-Allowed header, registration objects and how to unregister.

Registering is the step that tells the browser "this file is my service worker". It is a single method call, but several details decide whether it works: where the file lives, what scope it receives, when the call runs, and what you do with the result. This lesson covers each of them, plus how to inspect and remove registrations while you develop.

The basic call

JavaScript
if ('serviceWorker' in navigator) {
  window.addEventListener('load', async () => {
    try {
      const registration = await navigator.serviceWorker.register('/sw.js');
      console.log('Registered with scope:', registration.scope);
    } catch (error) {
      console.error('Service worker registration failed:', error);
    }
  });
}

Points worth noting:

  • Feature detection keeps the page working in browsers without service workers.
  • Waiting for load is a performance courtesy. Registration starts a background download and install that competes for bandwidth and CPU with the page's own resources. Registering after load protects your first paint. For a heavy page, you can wait even longer, for example until the browser is idle.
  • register() returns a promise for a ServiceWorkerRegistration. It resolves when the registration succeeds, which is earlier than when the worker has finished installing. A failing registration (404, a syntax error, an insecure origin) rejects.
  • Calling register() again with the same URL is harmless: the browser sees the existing registration and moves on. You can call it on every page load; that is how update checks happen.

Scope: which pages does the worker control?

The scope is the set of URLs whose pages and requests the worker handles. By default the scope is the folder that contains the worker file:

Worker URL Default scope Controls
/sw.js / The whole origin
/app/sw.js /app/ /app/ and below only
/js/sw.js /js/ Only URLs under /js/

This is why the worker file belongs at the root. A worker in /js/sw.js cannot control the page /index.html.

You may request a narrower scope with the scope option:

JavaScript
navigator.serviceWorker.register('/sw.js', { scope: '/app/' });

A wider scope than the file's folder is not allowed unless the server sends the response header Service-Worker-Allowed: / for the worker script. That header is how you can keep the file in /js/ while still controlling the entire site.

The scope also controls the navigations, not only subresources. A page at /app/home is controlled when /app/ is in scope. A request from that controlled page to /api/data (outside the scope) still goes through the worker, because control is determined by the page, not the requested URL. Two registrations with nested scopes pick the most specific match for each page.

Computing a scope in code

The rule is a URL prefix match. You can experiment with it below. The stand-in finds the registration that controls a page, the same way the browser chooses the longest matching scope.

JS Stand-in: which registration controls this page?

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

No output.

Notice that /application is not in /app/: scope matching is by path prefix including the trailing slash.

The registration object

The registration describes the worker's current state. Its useful members:

  • registration.installing, .waiting, .active: the worker in each phase (or null).
  • registration.scope: the scope URL.
  • registration.update(): asks the browser to check for a new script right now.
  • registration.unregister(): removes the registration.
  • registration.showNotification(), registration.sync, registration.pushManager: connections to push and sync (later chapters).

You can also look up registrations later:

JavaScript
const reg = await navigator.serviceWorker.getRegistration();       // for this page
const all = await navigator.serviceWorker.getRegistrations();      // for the origin
const ready = await navigator.serviceWorker.ready;                 // waits for an active worker

navigator.serviceWorker.ready is handy: it resolves with a registration once a worker is active, so you can safely use it to subscribe to push or register sync tasks.

Options

register(url, options) supports a few options:

  • scope: described above.
  • type: 'classic' (default) or 'module'. A module worker allows import statements (supported in modern browsers; check support if you target old versions).
  • updateViaCache: 'imports' (default), 'all' or 'none'. It controls whether the HTTP cache is used when the browser checks for updates. 'none' is the safest for the worker script and its imports. Since 2019 the main script is already fetched bypassing the HTTP cache by default in modern browsers, but 'none' states the intention.
JavaScript
navigator.serviceWorker.register('/sw.js', {
  scope: '/',
  type: 'module',
  updateViaCache: 'none',
});

Controlled or not?

The first time a user visits, the page is not controlled because the worker registered during that page load. The page continues as a normal page; the worker installs and activates in the background. The worker controls the page after the next navigation or reload, or sooner if it calls clients.claim() in activate (next lesson). To check:

JavaScript
console.log(navigator.serviceWorker.controller);  // null if uncontrolled

Many offline bugs trace back to this: the developer tests the first load offline, finds nothing cached, and blames the cache. Reload once and test again.

Unregistering and cleaning up

During development, or if a bad worker has shipped, you need to remove registrations.

JavaScript
navigator.serviceWorker.getRegistrations().then((regs) => {
  regs.forEach((reg) => reg.unregister());
});

Unregistering does not delete caches. Also clear them: caches.keys().then((ks) => ks.forEach((k) => caches.delete(k))). In DevTools, Application > Storage > Clear site data does both at once. For a "kill switch" in production, publish a worker script that unregisters itself and clears caches, so users who had the bad worker are healed on their next update check.

JavaScript
// kill-switch sw.js
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', async () => {
  const keys = await caches.keys();
  await Promise.all(keys.map((k) => caches.delete(k)));
  await self.registration.unregister();
  const clients = await self.clients.matchAll();
  clients.forEach((c) => c.navigate(c.url));
});

Common registration problems

  • "SecurityError / insecure context": use HTTPS or localhost.
  • 404 on the script: the path is wrong, remember that /sw.js is absolute and sw.js is relative to the page.
  • Wrong MIME type: the script must be served with a JavaScript MIME type (not text/html, which happens when a catch-all route returns your index page for a missing file).
  • Scope error: requesting a scope above the file's folder without Service-Worker-Allowed.
  • Redirects: the worker script URL must not redirect.
  • Syntax errors in the worker: the install fails and the old worker stays; check the DevTools Console.

A guarded registration helper

Production code usually wraps registration in a helper that handles timing and failure and reports status. This stand-in shows the pattern with a fake navigator.serviceWorker, so you can see the flow (including failure) running.

JS Stand-in: a safe registration helper

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A worker is at /js/sw.js with no extra options or headers. What is its default scope?

    The default scope is the folder of the worker script.
  2. 2. How can a worker in /js/sw.js control the whole site?

    Widening the scope beyond the script's folder requires the Service-Worker-Allowed response header.
  3. 3. Why is it common to register the worker after the window load event?

    Registration starts downloads and work in the background that can slow the initial page.
  4. 4. After a first-time visit, navigator.serviceWorker.controller is null. Why?

    A page is controlled only if a worker was active when it loaded or if the worker claims it.

Summary

  • Register with navigator.serviceWorker.register(url, options) after feature detection, usually after load.
  • Default scope is the script's folder; widen it only with Service-Worker-Allowed.
  • The registration object exposes installing, waiting, active, update() and unregister(); navigator.serviceWorker.ready waits for an active worker.
  • A first visit is uncontrolled until reload or clients.claim().
  • Unregister and clear caches to remove a bad worker; ship a kill-switch worker if needed.

Next: Install and Activate Events