0Pricing
JavaScript Academy · Lesson

Caching Strategies

Apply cache-first and network-first patterns.

Caching Strategies is a free JavaScript Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Strategies Matter

Different assets need different handling. A logo can be served from cache forever; an API feed must be fresh. A caching strategy decides whether to try the cache or the network first, and how to combine them.

Cache-First

Cache-first: check the cache; if found, return it; otherwise fetch from the network. Ideal for static, rarely-changing assets like fonts, CSS, and images.

async function cacheFirst(request) {
  const cached = await caches.match(request);
  return cached || fetch(request);
}

Cache-First With Fallback Caching

On a cache miss you can fetch and also store the result so the next request is fast. This warms the cache lazily as users browse.

async function cacheFirst(request) {
  const cached = await caches.match(request);
  if (cached) return cached;
  const fresh = await fetch(request);
  const cache = await caches.open('runtime');
  cache.put(request, fresh.clone());
  return fresh;
}

Network-First

Network-first: try the network; if it succeeds, use and cache it; if it fails (offline), fall back to the cache. Best for frequently updated content like news or dashboards.

async function networkFirst(request) {
  try {
    const fresh = await fetch(request);
    const cache = await caches.open('runtime');
    cache.put(request, fresh.clone());
    return fresh;
  } catch (err) {
    return caches.match(request);
  }
}

Stale-While-Revalidate

Stale-while-revalidate: return the cached copy immediately for speed, while fetching a fresh copy in the background to update the cache for next time. A great balance of speed and freshness.

async function staleWhileRevalidate(request) {
  const cache = await caches.open('runtime');
  const cached = await cache.match(request);
  const network = fetch(request).then(res => {
    cache.put(request, res.clone());
    return res;
  });
  return cached || network;
}

Network-Only and Cache-Only

Two simple extremes:

  • Network-only: always fetch, never cache (e.g. analytics beacons).
  • Cache-only: only serve precached assets, never hit the network (e.g. an app shell).
// network-only:
// return fetch(request);
// cache-only:
// return caches.match(request);

Routing by Request Type

Real apps pick a strategy per request. Inspect request.url or request.destination in the fetch handler and route accordingly.

self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);
  if (url.pathname.startsWith('/api/')) {
    event.respondWith(networkFirst(event.request));
  } else {
    event.respondWith(cacheFirst(event.request));
  }
});

Handling Offline Fallbacks

When both network and cache miss, return a friendly offline page or placeholder instead of a broken response.

async function withOfflineFallback(request) {
  return (await caches.match(request)) ||
         (await caches.match('/offline.html'));
}

Caching Only Successful Responses

Avoid caching errors. Check response.ok (or status) before storing, so a 404 or 500 does not poison your cache.

const fresh = await fetch(request);
if (fresh.ok) {
  cache.put(request, fresh.clone());
}
return fresh;

Choosing a Strategy

Match strategy to content:

  • Static assets: cache-first
  • Dynamic data: network-first
  • Mixed content: stale-while-revalidate

Most apps combine several via request routing.

Strategies Recap

Caching strategies let one service worker serve the whole app intelligently: instant static assets, fresh dynamic data, and graceful offline fallbacks, all chosen per request.

Quick Check

Test your understanding of caching strategies.

Recap

You learned caching strategies:

  • Cache-first for static assets.
  • Network-first for fresh dynamic data.
  • Stale-while-revalidate for speed plus freshness.
  • Route per request via request.url/destination.
  • Only cache successful responses; provide offline fallbacks.

Next, background sync and cache updates.

Frequently asked questions

Is the “Caching Strategies” lesson free?

Yes — the full text of “Caching Strategies” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Caching Strategies”?

Apply cache-first and network-first patterns. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start JavaScript Academy?

No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Caching Strategies” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this JavaScript Academy lesson?

Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Registering a Service Worker
  2. The Cache API
  3. Caching Strategies
  4. Background Sync and Updates
← Back to JavaScript Academy