Skip to main content
← πŸ“„ HTML & the platformΒ·Module A7 Β· Lesson 10
TaskAdd a script that registers /sw.js as a service worker, but only if navigator.serviceWorker exists.

Service workers: app shell + offline (intro)

75 XP6 min
Theory

A bird's-eye view (deep dive lives in JS track)

A service worker is JS that runs IN ITS OWN THREAD between your page and the network. It can:

  • Cache resources for offline use.
  • Intercept fetch requests and serve from cache.
  • Listen for push notifications.
  • Persist across page navigations.
<script>
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.register("/sw.js");
  }
</script>

/sw.js is the worker file. It runs at the SAME origin, in a separate thread, with NO direct access to the DOM.

A minimal SW

// /sw.js
self.addEventListener("install", (e) => {
  e.waitUntil(
    caches.open("v1").then(c => c.addAll(["/", "/app.js", "/styles.css"]))
  );
});

self.addEventListener("fetch", (e) => {
  e.respondWith(caches.match(e.request).then(r => r || fetch(e.request)));
});

That's a "cache-first" strategy: try the cache, fall back to network. Page works offline after the first load.

Constraints

  • Only registers on HTTPS (or localhost).
  • Same-origin scope by default.
  • No DOM access β€” pure data + fetch.

When you need it

Real PWAs (offline-first apps), push notifications, background sync. For most CRUD sites, the browser cache and a <link rel="preload"> are enough.

πŸ”’

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β€” card required, cancel anytime.

Sign up β€” free trial β†’

First 10 lessons in each track are free. No card needed for those.

← PreviousNext lesson β†’

Get one Python or web tip a day β€” by email

Short, hand-written, no spam. Unsubscribe in one click.