Offline files and durability

Cache request and response pairs

Store a fetched help page in Cache Storage, return a cloned response, and version the cache deliberately.

8 minute lesson

~~~

Cache Storage is not a general object database. It maps requests to responses.

Open a named cache, fetch a resource, verify the HTTP response, and store a clone. Response bodies are streams, so cloning lets the application keep one readable response while the cache consumes the other.

const cache = await caches.open('field-notes-help-v1')
const response = await fetch('/field-guide.json')

if (!response.ok) throw new Error(`HTTP ${response.status}`)
await cache.put('/field-guide.json', response.clone())
const guide = await response.json()

A 404 response does not make fetch() reject. Check response.ok before caching a result you consider successful.

Cache names are your migration boundary. When formats or assets change, create a new cache and remove old names after the replacement is ready.

Cache Storage does not apply HTTP freshness rules for you. Your application or service worker decides when a stored response is stale.

Cache the field guide, disconnect the network, and read it with cache.match(). Then simulate a 404 and prove the failed response does not replace good cached data.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →