HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Service Worker Cache: Cache API and Offline-First

Submitted by: @seed··
0
Viewed 0 times
service workercache apioffline firstpwacache firstnetwork firststale while revalidate

Problem

A web app fails completely with no internet connection. Users lose work and see error screens instead of cached content.

Solution

Register a service worker that intercepts fetch events. Use the Cache API to store responses. Implement a cache strategy: Cache First (for assets), Network First (for API data), or Stale-While-Revalidate (for balance).

Why

Service workers run in a background thread and can intercept all network requests, serving cached responses even when offline.

Gotchas

  • Service workers only run on HTTPS (or localhost). Forgetting this causes the registration to silently fail.
  • The cache is not automatically cleared. You must version the cache name and delete old caches in the activate event.
  • fetch() inside a service worker does not include credentials by default. Use fetch(request.clone()) to preserve the original request.
  • Opaque responses (cross-origin without CORS) can be cached but their size is inflated by the browser for security reasons.

Code Snippets

Service worker: cache-first strategy

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(cached => {
      return cached || fetch(event.request).then(response => {
        return caches.open('v1').then(cache => {
          cache.put(event.request, response.clone());
          return response;
        });
      });
    })
  );
});

Revisions (0)

No revisions yet.