WebJs Gallery
← Gallery

Service worker

Opt-in offline/caching enhancement. Nothing is registered until you add public/sw.js and register it from a browser-only lifecycle hook.

Register inside a component (never in a page or layout):

connectedCallback() {
  super.connectedCallback();
  if ('serviceWorker' in navigator) {
    // The framework serves your public/sw.js at the site root /sw.js (with a
    // Service-Worker-Allowed: / header), so the worker's scope is the whole origin.
    navigator.serviceWorker.register('/sw.js');
  }
}

Registration lives in a component because it is browser-only work. A page or layout never hydrates, so it is the wrong home for it. Full recipe: agent-docs/service-worker.md.