忽略 service worker 中的 ajax 个请求

Ignore ajax requests in service worker

我的应用程序具有 HTML、CSS 和 JS 的基本 'shell'。页面的主要内容是通过多次 ajax 调用 API 加载的,该 API 位于另一个 URL 到我的应用 运行 所在的那个。我已经设置了一个 service-worker 来缓存应用程序的主要 'shell':

var urlsToCache = [
  '/',
  'styles/main.css',
  'scripts/app.js',
  'scripts/apiService.js',
  'third_party/handlebars.min.js',
  'third_party/handlebars-intl.min.js'
];

并在请求时使用缓存版本进行响应。我遇到的问题是我的 ajax 调用的响应也被缓存了。我很确定我需要向 service-worker 的 fetch 事件添加一些代码,这些代码总是从网络中获取它们而不是在缓存中查找。

这是我的 fetch 活动:

self.addEventListener('fetch', function (event) {
    // ignore anything other than GET requests
    var request = event.request;
    if (request.method !== 'GET') {
        event.respondWith(fetch(request));
        return;
    }

    // handle other requests
    event.respondWith(
        caches.open(CACHE_NAME).then(function (cache) {
            return cache.match(event.request).then(function (response) {
                return response || fetch(event.request).then(function (response) {
                    cache.put(event.request, response.clone());
                    return response;
                });
            });
        })
    );
});

我不确定如何忽略对 API 的请求。我试过这样做:

if (request.url.indexOf(myAPIUrl !== -1) {
  event.respondWith(fetch(request));
  return;
}

但是根据 Chrome Dev Tools 中的网络选项卡,所有这些响应仍然来自 service-worker。

您不必使用 event.respondWith(fetch(request)) 来处理您想要忽略的请求。如果您 return 没有调用 event.respondWith 浏览器将为您获取资源。

您可以这样做:

if (request.method !== 'GET') { return; }
if (request.url.indexOf(myAPIUrl) !== -1) { return; }

\ handle all other requests
event.respondWith(/* return promise here */);

IOW 只要您可以同步确定您不想处理请求,您就可以 return 来自处理程序并让默认请求处理接管。 Check out this example.