Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Browser and Web APIs

Service Workers

Reference for service workers: register(), the install, activate and fetch events, the Cache API, caching strategies, updates and the rules that apply.

A service worker is a script that the browser runs in the background, separate from any page. It sits between your site and the network: once it controls a page, it can intercept every fetch request from that page and answer it from a cache, from the network, or with something it builds itself. That is what makes offline pages, instant repeat visits and installable web apps possible.

A service worker has no DOM access, runs only on HTTPS (or localhost), and is event-driven: the browser starts it when needed and stops it when idle, so never keep state in its variables. Pages register it with navigator.serviceWorker.register(), and the worker itself is a plain script file that listens for install, activate and fetch.

JavaScript
if ("serviceWorker" in navigator) {
  navigator.serviceWorker.register("/sw.js");
}

Try it

Service workers cannot be registered from the sandboxed editors on this site. The first example shows the registration attempt and its error handling; the second tests the cache-first logic of a fetch handler against a plain Map, so you can see the strategy without a browser worker.

JS Registering with feature detection

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

No output.

JS Cache-first and network-first strategies

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

No output.

The real worker script is a separate file. This is the common shape, shown read-only because it needs a real service worker:

JavaScript
// sw.js
const CACHE = "site-v1";

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE).then((cache) => cache.addAll(["/", "/offline.html", "/app.css"]))
  );
});

self.addEventListener("activate", (event) => {
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
    )
  );
});

self.addEventListener("fetch", (event) => {
  if (event.request.method !== "GET") return;
  event.respondWith(
    caches.match(event.request).then((hit) => hit || fetch(event.request))
  );
});

Syntax

JavaScript
navigator.serviceWorker.register(scriptURL, options)
navigator.serviceWorker.getRegistration(scope)
registration.update()
registration.unregister()
self.skipWaiting()
clients.claim()
Name Description
scriptURL URL of the worker script. Its location limits its default scope: /sw.js can control the whole site, /app/sw.js only /app/.
options.scope A narrower path to control. It cannot be broader than the script's location unless the server sends Service-Worker-Allowed.
options.type "classic" (default) or "module".

Return value: register() returns a promise for a ServiceWorkerRegistration (properties scope, installing, waiting, active). It rejects with a TypeError or SecurityError for a bad URL, a failed fetch or an insecure context.

Lifecycle events: install (cache your files), activate (clean up old caches), fetch (answer requests), plus message, push and notificationclick.

Usage notes

  • Lifecycle first. A new worker installs, then waits until no page uses the old one. skipWaiting() and clients.claim() change that, but may mix old pages with new code.
  • Wrap async work in event.waitUntil() or the browser may stop the worker before it finishes. Use event.respondWith() in fetch handlers.
  • Bump the cache name when you change cached files, and delete old caches in activate.
  • Pick a strategy per request type: cache-first for fingerprinted assets, network-first for HTML and APIs, stale-while-revalidate for things that can be slightly old.
  • Only cache GET requests. Never cache responses containing private user data in a shared cache.
  • The worker script is checked for changes on navigation and about once a day. Do not serve it with a long HTTP cache lifetime.
  • Debugging. Use the Application panel in DevTools to unregister, update and inspect caches.

Browser support

Service workers are supported in all current browsers. Features around them, such as Push and Background Sync, vary a lot, so check a compatibility table for each.