ReviseAlgo Logo

Browser APIs & Web APIs

Service Workers & Caching Basics

Master offline web capabilities using Service Workers. Learn service worker registration, lifecycle events, intercepting network requests, and cache storage management.

Last Updated: July 15, 2026 12 min read

1. Introduction

A Service Worker is a specialized type of web worker that acts as a proxy between the browser, the network, and the local cache. It enables features like offline support, push notifications, and background data synchronization.

2. Why It Matters

Service Workers are the foundation of Progressive Web Apps (PWAs). They allow you to intercept network requests, serve cached assets instantly, and provide offline support, ensuring your application runs smoothly even on unstable network connections.

3. Real-World Analogy

Think of a Personal Courier on a Remote Island:

  • Traditional Network (Direct Delivery): You send a request to a store on the mainland. If the ferry is cancelled (network is offline), your request fails, and you receive nothing.
  • Service Worker (Local Courier + Warehouse): You hire a courier who lives on the island.
    1. When you need an item, you ask the courier (network request intercepted).
    2. The courier checks their local warehouse (Cache Storage) first. If the item is in stock, they deliver it to you instantly, without waiting for the mainland ferry.
    3. If the item is missing, the courier sails to the mainland (network request), delivers the item to you, and saves a copy in the warehouse for next time.

4. Registration and Lifecycle

To use a Service Worker, register it in your main application script. The browser then manages its lifecycle: Register -> Install -> Activate.

5. Intercepting Requests (Fetch)

Once activated, the Service Worker intercepts all network requests from pages under its scope, allowing you to serve cached responses instead of sending network requests:

6. Practical Example

This script demonstrates implementing a Network-First caching strategy, falling back to the cached copy only if the network request fails:

7. Common Mistakes

  • Not serving sw.js from the root directory: Service Workers can only intercept requests within their directory scope. If you place sw.js in a subdirectory (like /js/sw.js), the service worker can only intercept requests that start with /js/. Place sw.js in the root directory to intercept all requests on your domain.
  • Running Service Workers on HTTP connections: Service workers can intercept network requests, making them highly powerful. To prevent malicious scripts from hijacking network traffic, browsers restrict Service Workers to secure contexts (HTTPS), except on localhost.

8. Quick Quiz

Q1: Which event listener inside a service worker is used to intercept outgoing network requests and serve cached assets instead?

A) install

B) fetch

Answer: B — The fetch event fires whenever the browser requests a resource, allowing the service worker to intercept the request and return a cached copy.

9. Scenario-Based Challenge

The Offline Offline fallback shell page:

An application should display a custom offline page: /offline.html if both the network request fails and the requested page is not in the cache. Design the fetch event listener inside your Service Worker to implement this fallback shell.

10. Debugging Exercise

Explain why modifying sw.js does not update the active service worker immediately, and how to resolve this during development:

// Developer changes SW file:
// sw.js -> added new console log statements
// Page is reloaded, but old console log logs print! Why?
View Solution

Diagnosis: When a service worker file is updated, the browser downloads and installs the new version, but keeps the old version active to prevent page crashes. Sibling tabs must be closed, or the user must navigate away, before the new service worker activates (the waiting state).

Fix: During development, check the "Update on reload" option in Chrome DevTools Application tab, or call self.skipWaiting() inside the install event handler to activate the new version immediately:

self.addEventListener('install', (e) => {
  self.skipWaiting(); // Skip waiting state
  e.waitUntil(caches.open(CACHE_NAME).then(c => c.addAll(ASSETS)));
});

11. Interview Questions

🟢 Q1: Describe the lifecycle of a Service Worker and when each stage runs.

Answer:
1. Registration: The main script registers the service worker using navigator.serviceWorker.register().
2. Installation (install event): Fires when the service worker is first downloaded. This is typically used to pre-cache core layout assets.
3. Activation (activate event): Fires once the service worker takes control of the page. This is used to clean up old caches from previous versions.
4. Idle/Active: The service worker runs in the background, intercepting requests and handling events (like fetch, push, or sync).

12. Production Considerations

  • Cache Invalidation: Define unique cache names matching the service worker version (e.g. 'v1-assets', 'v2-assets'). During the activate event, delete old caches to free storage and ensure users receive the latest assets.