Service worker registration and scope
Quick answer
A service worker is an event-driven browser worker that can control eligible pages and handle their requests. Registration associates a script with a scope.
How it works
On a secure context (HTTPS or a trustworthy local development origin), call navigator.serviceWorker.register("./sw.js", {scope:"./"}). The script must be an allowed same-origin resource. The registration promise does not imply that a new worker is already controlling the current page. navigator.serviceWorker.ready resolves when an associated registration has an active worker. navigator.serviceWorker.controller reports the current controller, if any. Use an isolated development origin and the supplied offline-lab files for these examples.
Local examples
Run in the isolated secure-origin offline-lab page; NOT RUN in local validation. See projects/offline-lab/README.md.
(async () => {const r=await navigator.serviceWorker.register("./sw.js",{scope:"./"});console.log(r.scope===new URL("./",location.href).href);})()Expected console output (not executed locally):
trueRegistration scope matches the directory URL in the supplied lab.
Run in the isolated secure-origin offline-lab page; NOT RUN in local validation. See projects/offline-lab/README.md.
(async () => {await navigator.serviceWorker.register("./sw.js");const r=await navigator.serviceWorker.ready;console.log(Boolean(r.active));})()Expected console output (not executed locally):
trueAn active worker is present when ready resolves.
Common mistakes
Never register a broad-scope service worker on an unrelated production site. The blank-document sandbox used for validation cannot execute registration; run these examples only in the supplied local lab.
Practice
Serve the offline-lab directory locally, register sw.js, inspect the scope, and reload before checking controller.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Service worker registration and scope — Knowledge Check
Apply the concept and reason about local example output.
What does a resolved register() promise identify?
What should you inspect to determine whether the current page is controlled?
Why use a separate origin for service worker practice?
What is the expected console output of Service worker registration and scope example 1?
(async () => {const r=await navigator.serviceWorker.register("./sw.js",{scope:"./"});console.log(r.scope===new URL("./",location.href).href);})()What is the expected console output of Service worker registration and scope example 2?
(async () => {await navigator.serviceWorker.register("./sw.js");const r=await navigator.serviceWorker.ready;console.log(Boolean(r.active));})()