JavaScript Notes
Master JavaScript Service Workers for offline support, caching strategies, push notifications, and PWA features. Learn install/activate/fetch lifecycle with real examples and interview Q&A.
A Service Worker is a JavaScript file that runs in its own background thread — separate from the page — acting as a programmable network proxy. It can intercept every network request, serve cached responses, handle push messages, and sync data in the background. Service Workers are the backbone of Progressive Web Apps (PWAs).
💡 Requirements: Service Workers require HTTPS (or localhost) and are scoped to the directory they are placed in. They run in a separate thread with no DOM access.
Service Worker Lifecycle
Registering a Service Worker
// In your main page script (app.js)
async function registerSW() {
if (!("serviceWorker" in navigator)) {
console.warn("Service Workers not supported");
return;
}
try {
const registration = await navigator.serviceWorker.register("/sw.js", {
scope: "/" // controls requests under this path
});
console.log("SW registered:", registration.scope);
} catch (error) {
console.error("SW registration failed:", error);
}
}
registerSW();"SW registered: https://example.com/"
The Service Worker File (sw.js)
Install Event — Pre-cache Assets
"[SW] Installing..." "[SW] Pre-caching assets" // All listed assets are downloaded and stored in Cache Storage
Activate Event — Clean Old Caches
"[SW] Activating..." "[SW] Deleting old cache: v0-static-cache" // Old caches are removed; SW takes control of all clients
Fetch Event — Intercept Requests
Caching Strategies
1. Cache First (Offline First)
Serve from cache; fall back to network if not cached.
"[SW] Cache hit: /styles.css" // served from cache instantly "[SW] Cache miss, fetching: /api/news" // fetched from network and cached
Best for: Static assets (JS, CSS, images, fonts)
2. Network First
Try network; fall back to cache if offline.
// Online: fetches fresh data and updates cache "[SW] Offline, serving from cache: /api/user" // when network fails
Best for: API responses, dynamic content
3. Stale While Revalidate
Serve cache immediately; update cache in background.
// User sees cached content instantly // Background fetch updates the cache for next visit
Best for: Assets that can be slightly stale (avatars, non-critical API data)
Strategy Decision Chart
When to Use Service Workers
- Offline support — show app even without internet
- Performance — serve assets from cache, skip network for static files
- Background sync — queue form submissions when offline, send when back online
- Push notifications — receive server push messages when page is closed
- PWA installability — required for "Add to Home Screen" feature
Service Worker vs Web Worker
| Service Worker | Web Worker | |
|---|---|---|
| Purpose | Network proxy, caching | CPU-heavy background computation |
| DOM access | ❌ No | ❌ No |
| Intercepts requests | ✅ Yes | ❌ No |
| Tied to page lifecycle | ❌ No (survives page close) | ✅ Yes |
| Multiple per origin | ❌ One per scope | ✅ Many |
Common Mistakes
- Not using HTTPS — Service Workers are blocked on insecure origins (except localhost).
- Caching POST requests — the Cache API only caches GET responses. Never cache auth or mutation requests.
- Not versioning the cache — without versioning (
v1,v2), old stale assets serve forever. - Forgetting
event.waitUntil()— without it, the browser can terminate the SW before async work completes. - Scope misunderstanding — a SW at
/admin/sw.jsonly controls requests under/admin/. Place it at the root/sw.jsfor full-site control. - Not handling the offline page fallback — always cache and serve
/offline.htmlfor navigation failures.
Interview Questions
Q1. What is a Service Worker and what makes it unique?
A Service Worker is a JavaScript file that runs in a background thread, separate from the page. It acts as a network proxy — intercepting fetch requests, serving cached responses, and enabling push notifications and background sync. It survives page closure and requires HTTPS.Q2. What are the three lifecycle events of a Service Worker?
install(first setup, pre-cache assets),activate(old SW replaced, clean old caches),fetch(intercept every network request).
Q3. What is event.waitUntil() and why is it necessary?
waitUntil(promise) tells the browser to keep the Service Worker alive until the promise resolves. Without it, async operations (like opening caches) may be cut short when the SW event handler returns.Q4. What is the difference between Cache First and Network First strategies?
Cache First serves from cache immediately (fast, works offline) and falls back to network only if not cached — best for static assets. Network First always tries the network for fresh data and falls back to cache only if offline — best for dynamic API responses.
Q5. What does self.skipWaiting() do?
It tells a newly installed Service Worker to immediately become active without waiting for the existing SW to release all clients. Used with clients.claim() to take control of pages right away.Q6. How do you update a Service Worker?
The browser checks for an updatedsw.json every page load (byte-by-byte comparison). If different, the new SW installs alongside the old one, waits until all tabs close, then activates. To force immediate update, useskipWaiting()+clients.claim().
Q7. Can a Service Worker access the DOM?
No. Service Workers run in a completely separate thread with no access towindow,document, or the DOM. They communicate with pages viapostMessage.
Q8. What is Background Sync in Service Workers?
Background Sync (SyncManager) lets you defer requests until the user has a stable connection. For example, if a user submits a form offline, the SW queues it and automatically retries when connectivity is restored.Key Takeaways
- Service Workers are background proxies — they intercept all network requests and can serve cached responses for offline support.
- The lifecycle: install (pre-cache) → activate (clean old caches) → fetch (handle requests).
- Always use
event.waitUntil()for any async operation inside SW events. - Choose the right caching strategy: Cache First for static assets, Network First for dynamic data, Stale While Revalidate for semi-fresh content.
- Service Workers require HTTPS and are scoped to their directory.
- They are the foundation of PWAs — enabling offline mode, push notifications, and installability.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Service Workers in JavaScript — Offline, Caching & PWA Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, browser, apis, service
Related JavaScript Master Course Topics