Service Worker Response Cache Headers

2020-07-09 03:36发布

问题:

I'm trying to figure out how the service worker works in regards to cache headers in responses. I have implemented a couple of service workers now but have never had to bother worrying about caching headers, how long items should be cached for etc. I'm now implementing it on an enterprise production site, whereby this stuff actually really matters.

Basically when using a service worker, is the http cache completely bypassed?

Do I then need to build a framework to handle resource expiration/invalidation like the http cache used to do for us? Or am I talking rubbish?

Would be super helpful if someone could provide some clarification of this. The way I see it there are 3 potential scenarios:

A). Network request => Service worker fetch => (Browser cache?) <=> Server

B). Network request <=> (Browser cache?) <=> Service worker fetch <=> Server

C). Network request => Service worker fetch <=> Server

I've tested this locally and it seems that C). is the correct implementation, whereby we the developer have sacrificed cache header/duration abstraction for control.

I'm fine with this, just want it clarifying before I run off and build a framework for reading and honouring caching headers in the service worker.

回答1:

A) is the correct model. If a service worker controls a page, all network requests will trigger the fetch event handler of the service worker prior to consulting the browser cache or the network.

In turn, any time the service worker makes a network request, either explicitly via fetch() or implicitly via cache.add()/cache.addAll(), the browser's "traditional" cache is consulted for a response first. A network request to the server will only be made if there isn't a valid response in the browser cache.

This sometimes works in your favor, and sometimes can expose you to subtle bugs if you don't expect that behavior.

There's a very detailed explanation of this interaction at https://jakearchibald.com/2016/caching-best-practices/, specifically covering things to avoid and ways to take advantage of this behavior.



回答2:

That depends on how you configure request. With Fetch API you can control how request interacts with browser HTTP Cache.

For example you can set request's cache mode to no-store so it will bypass HTTP Cache. Or you can set request's cache mode to force-cache so browser will return cached response even if it is stale:

fetch("some.json", {cache: "force-cache"})
  .then(function(response) { /* consume the response */ });

By default request's cache mode is default. In this case request will act as usual. Obviously that is only if service worker actually performs request instead of returning some hardcoded response.

For more information check Fetch Standard, Request.cache MSN page and Using Service Workers MDN page.