仅在脱机时使用ServiceWorker缓存

Rub*_*Jr. 18 javascript browser-cache web-worker service-worker

我正在尝试将服务工作者集成到我的应用程序中,但我发现服务工作者即使在线也尝试检索缓存内容,但我希望它在这些情况下更喜欢网络.我怎样才能做到这一点?下面是我现在的代码,但我认为它不起作用.为简洁起见,省略了SW安装代码.

var CACHE_NAME = 'my-cache-v1';
var urlsToCache = [
  /* my cached file list */
];

self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

/* request is being made */
self.addEventListener('fetch', function(event) {
  event.respondWith(
    //first try to run the request normally
    fetch(event.request).catch(function() {
      //catch errors by attempting to match in cache
      return caches.match(event.request).then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
      });
    })
  );
});
Run Code Online (Sandbox Code Playgroud)

这似乎导致警告,比如The FetchEvent for "[url]" resulted in a network error response: an object that was not a Response was passed to respondWith().我是服务工作者的新手,所以对任何错误的术语或不良做法表示道歉,欢迎任何提示.谢谢!

Bre*_*hie 10

如果不对此进行测试,我的猜测是,respondWith()在没有缓存匹配的情况下,您无法正确解析.根据MDN,传递给的代码respondWith()应该"通过将响应或网络错误返回到Fetch来解决".那么为什么不尝试这样做:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    fetch(event.request).catch(function() {
      return caches.match(event.request);
    })
  );
});
Run Code Online (Sandbox Code Playgroud)

  • 另见Jake的离线烹饪书:https://jakearchibald.com/2014/offline-cookbook/#network-falling-back-to-cache (3认同)
  • 这段代码与我上面的代码基本相同,不幸的是会导致相同的错误:/ (2认同)
  • 鉴于这似乎是记录在案的方法,我将接受这一点并假设某处发生了可疑的事情......如果我发现更多,我会更新。 (2认同)

小智 5

为什么不为fetch事件打开缓存?我认为服务工作者的过程是:

  • 打开你的缓存

  • 检查请求是否与缓存中的答案匹配

  • 然后你回答

或(如果答案不在缓存中):

  • 通过网络检查请求

  • 从网络克隆你的答案

  • 将请求和克隆的答案放在缓存中以备将来使用

我会写:

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.open(CACHE_NAME).then(cache => {
     return cache.match(event.request).then(response => {
      return response || fetch(event.request)
      .then(response => {
        const responseClone = response.clone();
        cache.put(event.request, responseClone);
        })
      })
    }
 );
});
Run Code Online (Sandbox Code Playgroud)


Kal*_*lle 5

event.respondWith() 期望解析为 Response 的承诺。因此,在缓存未命中的情况下,您仍然需要返回 Response,但在上面,您什么都不返回。我也会尝试先使用缓存,然后再获取,但无论如何,作为最后的手段,您始终可以创建一个合成响应,例如这样的:

return new Response("Network error happened", {"status" : 408, "headers" : {"Content-Type" : "text/plain"}});
Run Code Online (Sandbox Code Playgroud)