freecoding.school100% FREE · NO SIGNUP
Input HarborISSUE #40 of 46

service workers · the offline surface

FormaVSCaptain Invalid Input
Forma saysA service worker is a background script that intercepts network requests — the engine behind offline pages and PWAs.

Registered once with navigator.serviceWorker.register('sw.js'), a service worker sits between your page and the network on its own thread. It listens for install, activate, and fetch events, and can serve cached responses so the app loads instantly and works offline.

It requires HTTPS (or localhost) and a separate script file, so it can't fully run in this inline sandbox. It's the foundation of Progressive Web Apps — pair it with a manifest and you have an installable, offline-capable web app.

Power-ups you unlock

Captain Invalid Input attacks — common mistakes

Boss battleWrite the registration + a fetch handler that serves from cache first. (Save sw.js as a real file and serve over https/localhost to see it work.)

Example code

<!doctype html>
<html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px">
  <pre id="out">service worker shape (needs https + sw.js file):</pre>
  <script>
    const out = document.getElementById('out');
    out.textContent += '\n\n// in your page:';
    out.textContent += '\nif ("serviceWorker" in navigator)';
    out.textContent += '\n  navigator.serviceWorker.register("/sw.js");';
    out.textContent += '\n\n// in sw.js:';
    out.textContent += '\nself.addEventListener("fetch", e =>';
    out.textContent += '\n  e.respondWith(caches.match(e.request)';
    out.textContent += '\n    .then(r => r || fetch(e.request))));';
  </script>
</body></html>
▶ Open the interactive comic issue
‹ Structured Data · Json-Ld · Schema.OrgManifest · Turning A Page Into An App ›