๐Ÿ”น What is a Service Worker?

A Service Worker is a JavaScript file that runs in the background, separate from the main browser thread.
It acts like a proxy between the browser and the network, giving you control over:


๐Ÿ”น Where does it run?

  • Not in the DOM (i.e., it canโ€™t access window, document, etc.)

  • Runs in a separate thread, independently of the webpage

  • Continues running even when the webpage is closed (in limited ways)


๐Ÿ”น What Can a Service Worker Do?

CapabilityDescription
Intercept RequestsCatch and respond to network requests using cache or fetch
Offline CachingServe cached assets when offline
Push NotificationsSend messages to users even when the app is closed
Background SyncRetry failed requests when connection is restored
Asset PreloadingCache assets during installation for faster loads

๐Ÿ”น Basic Lifecycle of a Service Worker:

  1. Registration
    In your JS:
navigator.serviceWorker.register('/sw.js');
  1. Installation
    The browser installs the service worker (only once).

  2. Activation
    Cleans up old caches, takes control of the page.

  3. Fetch Events
    Starts intercepting requests:

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

๐Ÿ”น Cache Strategies (Simplified):

StrategyWhen to Use
Cache FirstFor static assets (logo, fonts, etc.)
Network FirstFor dynamic content (API data)
Stale While RevalidateServe from cache, update in background

๐Ÿ”น Limitations:

  • Only works over HTTPS (except on localhost)

  • Limited access to browser features (no DOM, no alerts)

  • Complex to debug sometimes


๐Ÿ”น Common Real-World Use:

  • PWAs like Twitter Lite, Starbucks, Flipkart Lite

  • Offline access to websites

  • Faster repeat visits

  • Sending notifications like WhatsApp Web or Gmail