首页 > 解决方案 > 是否可以手动添加到服务工作者缓存?

问题描述

我正在尝试制作一个与服务工作者一起使用的接口,但它目前希望能够写入缓存本身。

如果不可能,那么了解在网络不可用时是否会使用过期的缓存资源会很有帮助。

专门 编辑Response公共构造函数不允许指定正文数据,并且Cache.put()需要一个Response.

标签: dartservice-worker

解决方案


I am trying to make an interface that works with service worker but it currently expects to be able to write to the cache itself.

The Cache Storage API is useful inside of a service worker, but it isn't limited to just the ServiceWorkerGlobalScope. It's also exposed on normal web pages as window.caches. So you can read from and write to the same caches from either your web page or your service worker (or a web worker, for that matter).

If it is not possible, it would be helpful to know if an expired cache resource will be used when network is unavailable.

There's no concept of "expired cache resource" within the Cache Storage API. The Cache-Control headers in the cached Response are effectively ignored, if that's what you're asking about. So as long as a Response is stored in a cache, you can read it and make use of it. But nothing will be used automatically—you need to specifically set up a service worker's fetch event handler and add in logic that determines what happens in various scenarios. A good, generic overview of how to write that service worker code can be found in "The Offline Cookbook".

For instance, here's a fetch handler that will respond to all network requests by first going against the network (via fetch()) and if that rejects, tries to respond with a cached response for the same URL:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    fetch(event.request).catch(function() {
      return caches.match(event.request);
    })
  );
});

推荐阅读