Preskoči na glavni sadržaj
← 📄 HTML & the platform·Modul A7 · Lekcija 10
ZadatakAdd a script that registers /sw.js as a service worker, but only if navigator.serviceWorker exists.

Uslužni radnici: ljuska aplikacije + offline (uvod)

75 XP6 min
Teorija

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.

🔒

Registriraj se i počni kodirati

Teorija je otvorena svima. Editor, pregled uživo i provjera otključavaju se s 7-dnevnim besplatnim probnim periodom — potrebna kartica, otkaži kad god.

Registracija — besplatan probni period →

Prvih 10 lekcija u svakom smjeru je besplatno. Bez kartice.

← PrethodnaSljedeća lekcija →

Jedan Python ili web savjet dnevno — emailom

Kratko, ručno pisano, bez spama. Odjavi se jednim klikom.