Skip to main content

Service Worker Caching

What It Is

Service worker caching means using a service worker to intercept network requests and serve cached resources when available.

A service worker runs in the background, separate from the web page, and acts like a proxy between the web app, browser, cache, and network.

Service Worker Caching = Service worker intercepts requests and responds from cache or network

Why It Matters

Service worker caching helps create faster and more reliable web applications.

It can improve the app by:

  • reducing network calls
  • serving cached files faster
  • supporting offline functionality
  • improving repeat visits
  • handling network availability better
Without cache -> request goes to network
With service worker cache -> request can be served locally

This is useful for offline-first applications and Progressive Web Apps.


How It Works

Service worker caching follows a simple request-handling flow.

1. Page makes a network request
2. Service worker intercepts the request
3. Service worker checks cache for the requested resource
4. If resource exists, return it from cache
5. If resource does not exist, fetch it from network
6. Return the fetched resource to the page

The main idea is:

Cache first if possible, network if needed

Service Worker as a Proxy

A service worker sits between the page and the network.

Page -> Service Worker -> Cache / Network

Because it can intercept requests, it can decide whether to:

  • serve from cache
  • fetch from network
  • cache new resources
  • support offline fallback behavior

This gives developers control over request and caching behavior.


Basic sw.js Setup

A service worker cache usually starts with a cache name and a list of URLs to cache.

const CACHE_NAME = "my-cache-v1";

const urlsToCache = [
"/",
"/index.html",
"/styles.css",
"/app.js",
"/image.gif",
];

The cache name identifies the cache version.

The URL list contains files that should be stored in cache.

CACHE_NAME -> identifies the cache
urlsToCache -> files that should be cached

Install Event

The install event runs when the service worker is installed.

During this phase, the service worker opens a cache and adds the required URLs.

self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(urlsToCache);
}),
);
});

event.waitUntil() makes sure the service worker does not finish installing until the cache is created and the files are added.

Install event = prepare cached files before the service worker becomes ready

Fetch Event

The fetch event listens to every network request made by the page.

The service worker checks whether the requested resource already exists in cache.

self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
}),
);
});

If a cached response exists, it is returned immediately.

If not, the request continues to the network.

Cache hit -> return cached resource
Cache miss -> fetch from network

Complete sw.js Example

const CACHE_NAME = "my-cache-v1";

const urlsToCache = [
"/",
"/index.html",
"/styles.css",
"/app.js",
"/image.gif",
];

self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(urlsToCache);
}),
);
});

self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
}),
);
});

This service worker uses a simple cache-first behavior.

It checks the cache first and uses the network only when the requested resource is not cached.


Registering the Service Worker

The service worker file does not run automatically.

The page must register the sw.js file.

Before registering, check whether the browser supports service workers.

<script>
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/sw.js")
.then((registration) => {
console.log(
"Service Worker registered with scope:",
registration.scope,
);
})
.catch((error) => {
console.error("Service Worker registration failed:", error);
});
}
</script>

This connects the page with the service worker file.

Page script -> registers sw.js -> service worker can install and handle fetches

What Happens After Registration

After the service worker is registered:

1. Browser loads sw.js
2. Service worker install event runs
3. Cache named my-cache-v1 is opened
4. URLs are added to cache
5. Fetch event starts intercepting requests
6. Cached resources are returned from cache
7. Missing resources are fetched from network

This allows the app to reuse cached files instead of requesting them again.


Cache Hit

A cache hit happens when the requested resource already exists in cache.

Request -> Service Worker -> Cache found -> Return cached file

Example:

/styles.css exists in cache
Service worker returns /styles.css from cache
No network request needed

This improves speed and reduces network usage.


Cache Miss

A cache miss happens when the requested resource does not exist in cache.

Request -> Service Worker -> Cache not found -> Fetch from network

Example:

/new-image.png is not in cache
Service worker fetches it from network

In the PDF example, the service worker returns the fetched resource to the page.


Cached URLs

The example caches these URLs:

URLPurpose
/Root route
/index.htmlMain HTML page
/styles.cssStylesheet
/app.jsJavaScript file
/image.gifImage asset

These are static resources that are useful to cache because the page may need them repeatedly.


Important Methods

MethodPurpose
caches.open()Opens or creates a named cache
cache.addAll()Adds multiple URLs to cache
caches.match()Checks whether a request exists in cache
event.waitUntil()Waits for async install work to finish
event.respondWith()Controls the response for a fetch request
fetch()Makes a normal network request

Service Worker Caching Table

AreaExplanation
Main roleIntercepts requests and controls cache/network behavior
Runs whereBackground service worker thread
Cache setupDone during install event
Request handlingDone during fetch event
Cache hitResource is returned from cache
Cache missResource is fetched from network
Best forOffline support and faster repeat loads
Common filesHTML, CSS, JS, images

Basic Checklist

Create a sw.js file
Define a cache name
List URLs that should be cached
Use install event to open cache
Use cache.addAll to cache important files
Use event.waitUntil during install
Use fetch event to intercept network calls
Use caches.match to check cached resources
Return cached response when available
Use fetch when resource is not cached
Register sw.js from the page
Check serviceWorker support before registration

Interview Style Answer

Service worker caching is a technique where a service worker acts as a proxy between the web application, browser, cache, and network. It runs in the background and can intercept network requests made by the page. During the install event, the service worker opens a named cache and stores important URLs such as HTML, CSS, JavaScript, and images. During the fetch event, it checks whether the requested resource exists in cache. If it exists, the cached response is returned without making a network call. If it does not exist, the request is fetched from the network. The service worker must be registered from the page using navigator.serviceWorker.register("/sw.js").


One-Line Summary

Service Worker Caching = Cache important resources during install and serve cached responses during fetch.

Final Mental Model

Install -> open cache and save files
Fetch -> intercept requests
Cache hit -> return cached file
Cache miss -> fetch from network
Register -> connect page with sw.js