๐น 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:
-
Caching (offline support)
-
Background sync
๐น 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?
| Capability | Description |
|---|---|
| Intercept Requests | Catch and respond to network requests using cache or fetch |
| Offline Caching | Serve cached assets when offline |
| Push Notifications | Send messages to users even when the app is closed |
| Background Sync | Retry failed requests when connection is restored |
| Asset Preloading | Cache assets during installation for faster loads |
๐น Basic Lifecycle of a Service Worker:
- Registration
In your JS:
navigator.serviceWorker.register('/sw.js');-
Installation
The browser installs the service worker (only once). -
Activation
Cleans up old caches, takes control of the page. -
Fetch Events
Starts intercepting requests:
self.addEventListener('fetch', event => {
event.respondWith(caches.match(event.request));
});๐น Cache Strategies (Simplified):
| Strategy | When to Use |
|---|---|
| Cache First | For static assets (logo, fonts, etc.) |
| Network First | For dynamic content (API data) |
| Stale While Revalidate | Serve 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