仅在脱机时使用ServiceWorker缓存 [英] Use ServiceWorker cache only when offline

查看:139
本文介绍了仅在脱机时使用ServiceWorker缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to integrate service workers into my app, but I've found the service worker tries to retrieve cached content even when online, but I want it to prefer the network in these situations. How can I do this? Below is the code I have now, but I don't believe it is working. SW Install code is omitted for brevity.

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

这似乎导致像的警告[url]的FetchEvent导致网络错误响应:一个不是响应的对象被传递给respondWith()。我是服务工作者的新手,所以对任何错误的术语或不良做法表示歉意,欢迎任何提示。谢谢!

This seems to lead to warnings like The FetchEvent for "[url]" resulted in a network error response: an object that was not a Response was passed to respondWith(). I'm new to service workers, so apologies for any mistaken terminology or bad practices, would welcome any tips. Thank you!

推荐答案

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

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

这篇关于仅在脱机时使用ServiceWorker缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆