Service Worker: Fast Repeat Visits and an Offline Page
Need this adapted for your organization? Work with AstroWeb.dev — Astro services by NViewsWEB.
Feature

Service Worker: Fast Repeat Visits and an Offline Page

A generated sw.js precaches styles and the offline page, serves static assets cache-first, and registers itself after the page loads.

Repeat visits should not re-download the same CSS, fonts and images. The theme generates a service worker for that, so you configure it instead of writing it.

Generated, not hand-written

core/scripts/generate/sw.mjs runs in the prebuild step and writes:

  • public/sw.js, the worker,
  • public/offline.html, shown when a page cannot be reached,
  • an sw entry in src/data/manifest/config.json that records what was precached.

Because the file list comes from the build manifests (styles, scripts, search index, logos), hashed file names are always current. Do not edit public/sw.js by hand; it is overwritten.

Strategy

Request Behaviour
Page navigation Navigation preload, then network, then the offline page if both fail
Precache on install /, /offline.html, the /styles/*.css bundles, the search index JSON, logos (optional) and any extra URLs
Scripts, images, fonts, JSON Cache-first for same-origin GET requests; a new asset is cached the first time it is fetched

HTML is never served from the cache while the network works, so content updates appear on the next visit.

Registration

core/js/individual/worker-lazy-loader.js calls navigator.serviceWorker.register("/sw.js") when the page has loaded. It is a bundled, nonce-aware script from the script manifest, so no inline script is needed and the CSP stays strict. The same loader swaps the lazy stylesheets and fonts into place. See Self-hosted fonts.

Configuration

// src/site/config/functions.mjs
serviceWorker: {
  enabled: true,
  precache: {
    logos: true,    // precache generated logo files
    icons: false,   // keep the install small and stable
    urls: [],       // extra same-origin URLs
  },
},

Keep urls short. Everything listed is downloaded on first visit.

Workflow

  1. Edit the config above.
  2. Run pnpm run dev or pnpm run build so sw.js is regenerated.
  3. In browser developer tools, open Application, then Service Workers, and confirm it is activated.
  4. Switch to offline mode and reload: an already visited page loads its assets from cache and an unreachable page shows offline.html.
  5. While developing, use “Update on reload” or unregister the worker if you see stale assets.