Saltar al contenido principal
← 📄 HTML & the platform·Módulo A7 · Lección 10
TareaAdd a script that registers /sw.js as a service worker, but only if navigator.serviceWorker exists.

Trabajadores de servicio: shell de la aplicación + fuera de línea (introducción)

75 XP6 min
Teoría

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.

🔒

Regístrate para empezar a programar

La teoría está abierta a todos. El editor, la vista previa y el check se desbloquean con una prueba gratis de 7 días — se requiere tarjeta, cancela cuando quieras.

Registrarse — prueba gratis →

Las primeras 10 lecciones de cada ruta son gratis. No se necesita tarjeta.

← AnteriorSiguiente lección →

Recibe un consejo de Python o web al día — por email

Corto, escrito a mano, sin spam. Anula la suscripción en un clic.