Prejsť na hlavný obsah
← 📄 HTML & the platform·Modul A7 · Lekcia 10
ÚlohaAdd a script that registers /sw.js as a service worker, but only if navigator.serviceWorker exists.

Servisní pracovníci: prostredie aplikácie + offline (úvod)

75 XP6 min
Teória

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.

🔒

Zaregistruj sa a začni programovať

Teória je otvorená pre každého. Editor, živý náhľad a kontrola sa odomknú so 7-dňovou bezplatnou skúškou — karta potrebná, zruš kedykoľvek.

Registrácia — bezplatná skúška →

Prvých 10 lekcií v každej trase je zdarma. Karta nie je potrebná.

← PredchádzajúcaĎalšia lekcia →

Jeden tip k Pythonu alebo webu denne — e-mailom

Krátke, ručne písané, žiadny spam. Odhlásiť jedným klikom.