Use ServiceWorker cache only when offline

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-29 23:49:41

Without testing this out, my guess is that you're not resolving respondWith() correctly in the case where there is no cache match. According to MDN, the code passed to respondWith() is supposed to "resolve by returning a Response or network error to Fetch." So why not try just doing this:

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

Why don't you open the cache for your fetch event? I think the process of a service worker is :

  • Open your cache

  • Check if the request match with an answer in your cache

  • Then you answer

OR (if the answer is not in the cache) :

  • Check the request via the network

  • Clone your answer from the network

  • Put the request and the clone of the answer in your cache for future use

I would write :

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);
        })
      })
    }
 );
});

event.respondWith() expects a promise that resolves to Response. So in case of a cache miss, you still need to return a Response, but above, you are returning nothing. I'd also try to use the cache first, then fetch, but in any case, as the last resort, you can always create a synthetic Response, for example something like this:

return new Response("Network error happened", {"status" : 408, "headers" : {"Content-Type" : "text/plain"}});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!