HuntExams Academy logo
HTML/CSSAdvanced#storage#pwa

What is the Cache API and how does it relate to Service Workers?

Answer

The Cache API lets JavaScript store request/response pairs for offline access, typically used inside a Service Worker to implement offline-first strategies like cache-first or network-first for PWAs.

Example

caches.open('v1').then(cache => {
  cache.addAll(['/index.html', '/styles.css']);
});

Detailed explanation

The Cache API is a browser storage API that lets JavaScript persist Request/Response pairs and retrieve them later. Its main interfaces are CacheStorage, exposed through caches, and Cache, which represents a named collection of entries. Unlike the browser’s HTTP cache, it gives application code explicit control over what is stored, when cached responses are served, and when entries are removed. This makes it useful for offline pages, static assets, and selected API responses in Progressive Web Apps (PWAs).

A Service Worker is an event-driven script that runs separately from the page and can intercept requests from clients it controls. The Cache API supplies storage; the Service Worker supplies request-handling logic. They are separate features: the Cache API can also be used from a page in a secure context, and a Service Worker does not automatically cache anything. In a fetch event handler, event.respondWith() can return a cached response or a network response. Cache-first checks storage before fetching, while network-first attempts the network and falls back to storage if that attempt fails. The right strategy depends on freshness and offline requirements.

In the example, caches.open('v1') opens or creates a named cache, and cache.addAll() fetches and stores the listed resources. During Service Worker installation, this work is commonly passed to event.waitUntil() so installation waits for precaching to complete. Return or await the addAll() promise so failures propagate correctly. For runtime caching, cache.put(request, response) stores an explicitly supplied response. Responses have consumable bodies, so response.clone() is normally needed when both caching and returning the same fetched response.

Interviewers look for lifecycle and correctness awareness, not just API syntax. Cache entries do not automatically expire according to HTTP cache headers; applications must implement freshness and cleanup policies. Versioned cache names help deploy updates, and activation is a common place to delete obsolete caches owned by the application. Storage is quota-limited and may be evicted, so offline availability is not guaranteed forever. Avoid casually caching sensitive or user-specific responses, and remember that fetch() resolves for HTTP errors such as 500; network-first logic must explicitly decide whether those responses should trigger a fallback.

Key points to remember

  • The Cache API stores request/response pairs under application-controlled cache names.
  • Service Workers intercept controlled requests; caching requires explicit application logic.
  • Cache-first favours cached availability, while network-first favours fresh network responses.
  • Use event.waitUntil() for installation work and event.respondWith() to supply fetch responses.
  • Manage cache versions, response cloning, freshness, storage limits, and sensitive data deliberately.

Common mistakes candidates make

  • Assuming Service Workers automatically cache resources or that the Cache API is available only inside them.
  • Ignoring promise lifetimes during precaching or consuming a response body without cloning it before reuse.
  • Expecting automatic expiry from Cache-Control headers or treating every HTTP error as a rejected fetch promise.

Likely follow-up questions

How does the Cache API differ from the HTTP cache?

The browser manages its HTTP cache using HTTP caching rules and headers. The Cache API provides explicit JavaScript-controlled storage and does not automatically enforce freshness through those headers.

What is stale-while-revalidate?

It serves an available cached response immediately while fetching an updated response in the background for future requests. A Service Worker can use event.waitUntil() to keep the background update alive; on a cache miss, it generally waits for the network.

How should old caches be removed after an update?

Create a new versioned cache, then delete obsolete application-owned caches during the activate event using event.waitUntil(). Restrict deletion to your application's cache names because CacheStorage is shared within the origin.

Interview tip: Explain storage versus interception first, then walk through the example and contrast cache-first with network-first.

Related Interview Questions

1
HTML/CSSIntermediate#css#specificity

What is CSS specificity and how is it calculated?

Open
2
HTML/CSSBeginner#css#box-model

What is the CSS box model?

Open
3
HTML/CSSBeginner#css#box-model

What is the difference between margin and padding?

Open