Richard Maher
Richard Maher

Reputation: 41

Stop Service Worker Fetch Event caching specific files

I'm listening for fetch events in a Service Worker and would like to know when is the response to a fetch cached?

1) When the Fetch Event is triggered? PreventDefault() to stop it? 2) Do I need cache: no-store on my INIT parameter to my FETCH call? 3) Does it happen at event.respondWith() time?

I have a data delivery strategy that seeks to deliver data as fresh as possible and only go to cache if the network is slow. BUT even then leave the network fetch running to update the cache whenever it finishes.

Without something like INIT "no-cache" aren't we at risk of the FETCH just reading cache anyway?

I (wrongly?) assumed caching was opt-in and I had to manually update the cache with a PUT().

Upvotes: 1

Views: 1738

Answers (2)

Marco Castelluccio
Marco Castelluccio

Reputation: 10782

From https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cache-lifetimes:

The Cache instances are not part of the browser’s HTTP cache

Don't confuse the HTTP cache with the caches of the Cache API.

The HTTP cache lives between the service worker and the network, so, if you want the browser not to cache (in the HTTP cache) the response, you have to use the 'no-store' option when fetching the resource.

The other caches instead are completely directly under your control, so if you don't store anything in them, you don't get anything from them.

Upvotes: 3

Richard Maher
Richard Maher

Reputation: 41

Spec says this should not be happening: -

https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cache-lifetimes

5.2. Understanding Cache Lifetimes

The Cache instances are not part of the browser’s HTTP cache. The Cache objects are exactly what authors have to manage themselves. The Cache objects do not get updated unless authors explicitly request them to be. The Cache objects do not expire unless authors delete the entries. The Cache objects do not disappear just because the service worker script is updated. That is, caches are not updated automatically. Updates must be manually managed. This implies that authors should version their caches by name and make sure to use the caches only from the version of the service worker that can safely operate on.

Upvotes: 1

Related Questions