0Pricing
HTML Academy · Lesson

Service Worker Registration from HTML

Register a service worker with a script tag and navigator API.

What a Service Worker Is

A service worker is a JavaScript file that runs in the background, separate from any page, intercepting network requests for its scope. It powers offline support, push notifications, background sync, and faster repeat loads via caching.

Registration

Register the worker from a page script: navigator.serviceWorker.register("/sw.js"). The browser fetches /sw.js, parses it, runs its install event, and starts intercepting requests for the registration's scope.

if ("serviceWorker" in navigator) {
  navigator.serviceWorker.register("/sw.js")
    .then((reg) => console.log("Registered, scope:", reg.scope))
    .catch((err) => console.error("Registration failed:", err));
}

All lessons in this course

  1. The Web App Manifest
  2. Service Worker Registration from HTML
  3. Theme Color and App Icons
  4. Offline Fallback Page
← Back to HTML Academy