Cosa serve

Un progetto Astro già funzionante e un file sw.js da mettere in public/.

Passo 1 — Creare il Service Worker

Crea il file public/sw.js:

const VERSION = "v1";
const PRECACHE = ["/", "/offline.html"];

self.addEventListener("install", (event) => {
  event.waitUntil(caches.open(VERSION).then((c) => c.addAll(PRECACHE)));
});

self.addEventListener("fetch", (event) => {
  event.respondWith(
    fetch(event.request).catch(() => caches.match(event.request))
  );
});

Passo 2 — Registrare il Service Worker

In BaseLayout.astro aggiungi prima di </body>:

<script is:inline>
  if ("serviceWorker" in navigator) {
    window.addEventListener("load", () => {
      navigator.serviceWorker.register("/sw.js");
    });
  }
</script>

Passo 3 — Provare

npm run build && npm run preview, apri DevTools → Application → Service Workers. Dovresti vedere il SW registrato. Disconnetti la rete e ricarica: la home si apre lo stesso.

Note

  • Il SW funziona solo su HTTPS (o localhost)
  • Cambia VERSION ogni release per invalidare la cache
  • Per una configurazione completa (PWA installabile, manifest, icone) servono altri pezzi che vedremo in un articolo dedicato