SyntaxStudy
Sign Up
JavaScript Advanced 6 min read

The Cache API

Cache API

The Cache API stores HTTP request/response pairs for offline use. It is typically used in Service Workers to cache assets and API responses.

Example
// In a Service Worker
self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open("v1").then((cache) => {
      return cache.addAll(["/", "/app.js", "/styles.css"]);
    })
  );
});

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

The Cache API + Service Worker combination is what enables Progressive Web Apps (PWAs) to work offline.