What is a Service Worker?

  • A script that runs in background (separate from main thread).
  • Intercepts network requests, caches responses.
  • Enables:
  • Offline apps
  • Push notifications
  • Background sync

Registering a Service Worker

if ("serviceWorker" in navigator) {
  navigator.serviceWorker
    .register("/sw.js")
    .then(() => console.log("Service Worker Registered"));
}

Basic Service Worker

const CACHE_NAME = "site-cache-v1";
const ASSETS = ["/", "/index.html", "/styles.css", "/app.js"];

self.addEventListener("install", (event) => {
  event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(ASSETS)));
});

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

Adding PWA Features

  • manifest.json
{
  "name": "My App",
  "short_name": "App",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#317EFB",
  "icons": [
    { "src": "/icon.png", "sizes": "192x192", "type": "image/png" }
  ]
}
  • Installable via “Add to Home Screen”.

Best Practices

  • Use Workbox for easier caching strategies.
  • Cache only what’s needed.
  • Provide fallbacks (offline.html).