advanced
Service Workers
Intercept network requests, implement offline behavior, cache assets, manage lifecycle, and avoid stale-update traps.
A service worker is a separate script that can intercept fetches, cache responses, support offline flows, and receive some background events. Its install, activate, and update lifecycle is deliberately conservative. Production answers should describe cache versioning, stale content, scope, HTTPS requirements, and clear fallback behavior.
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((cached) => cached ?? fetch(event.request))
);
});
Skip waiting and clients.claim change how fast updates take control — use deliberately. Never cache personalized responses without Vary and invalidation strategy.
On interviews: lifecycle awareness and the difference between caching for resilience and hiding broken deployments.
Common pitfalls: a bad service worker can keep serving stale code. Caching authenticated responses without care can leak data between sessions.
The trade-off is convenience versus control — pick the mechanism that matches your coupling and performance budget.
Checklist:
- Version named caches; delete old on activate.
- Define offline fallback routes.
- Respect scope and HTTPS requirements.
- Test update flows across reloads.