2

I haven't found a clear answer to this but from my experiments the following appears true:

Service workers have no access to or control over the traditional browser cache. Is this intended? Are there ways to do this that I haven't discovered yet?

When I say "browser cache" I don't mean the CacheStorage API. I do know that the service worker has full access to the CacheStorage API. I mean the cache which is used when requests in the network tab of browser dev tools say "from memory cache" as opposed to "from service worker" or just straight up from an actual network request.

derpedy-doo
  • 1,097
  • 1
  • 18
  • 22

1 Answers1

2

If by "browser cache" you mean the http cache, then yes the service worker can access it using the fetch() function. To control how it interacts with the http cache you can specify a RequestCache enumeration value in your request initializer. So something like:

// completely bypass the http cache when loading url
let r = new Request(url, { cache: 'no-store' });
fetch(r);

// revalidate any http cache entry for url
fetch(url, { cache: 'no-cache' });

// force use of the http cache entry even if its stale, otherwise load from network
fetch(url, { cache: 'force-cache' });

// Only return a response if the http cache entry is present.  Throws for cross-origin
// URLs.
fetch(url, { mode: 'same-origin', cache: 'only-if-cached' });

This shows both the full method of creating a Request object and the shorthand of using fetch() directly. The cache values can be passed in either case.

The fetch spec contains the full list of RequestCache values:

https://fetch.spec.whatwg.org/#requestcache

There is no direct programatic API to inspect or modify the http cache.

Ben Kelly
  • 1,304
  • 7
  • 9
  • Okay, yes, but there's no API available to the service worker to see what is cached or to manually cache anything into the http cache right? It's only automatically handled by the browser and out of the website dev's control (besides the use of headers as you mentioned). – derpedy-doo Jul 25 '19 at 15:55
  • You can use `cache: 'only-if-cached'` to see if a same-origin URL is in the cache. But otherwise you are correct. – Ben Kelly Jul 25 '19 at 16:05
  • 1
    Also, its difficult to determine if a `fetch()` response came out of http cache or came from the network. Generally you have to use the Performance API to inspect the `PerformanceResourceTiming.transferSize` attribute. If it came from http cache then the transfer size is zero and non-zero for network. This may not be interoperable across browsers, though. – Ben Kelly Jul 25 '19 at 16:06