Sari la conținutul principal
← 📄 HTML & the platform·Modul A7 · Lecția 10
SarcinăAdd a script that registers /sw.js as a service worker, but only if navigator.serviceWorker exists.

Lucrători de servicii: app shell + offline (introducere)

75 XP6 min
Teorie

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.

🔒

Înregistrează-te pentru a începe să programezi

Teoria e accesibilă tuturor. Editorul, previzualizarea live și verificarea se deblochează cu o probă gratuită de 7 zile — card necesar, anulabilă oricând.

Înregistrare — probă gratuită →

Primele 10 lecții din fiecare traseu sunt gratis. Fără card.

← AnterioarăLecția următoare →

Primește un sfat Python sau web pe zi — prin email

Scurt, scris de mână, fără spam. Dezabonare cu un click.