我有一个带有 HTML、CSS 和 JS 基本“ shell ”的应用程序。页面的主要内容通过对 API 的多次 ajax 调用加载,该 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 调用的响应也被缓存。我很确定我需要向
fetch
添加一些代码service-worker 总是从网络中获取它们而不是在缓存中查找的事件。这是我的
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))
处理您想要忽略的请求。如果您不打电话就返回 event.respondWith
浏览器将为您获取资源。
您可以执行以下操作:
if (request.method !== 'GET') { return; }
if (request.url.indexOf(myAPIUrl) !== -1) { return; }
\\ handle all other requests
event.respondWith(/* return promise here */);
IOW 只要您可以同步确定您不想处理请求,您就可以从处理程序返回并让默认请求处理接管。 Check out this example.
关于service-worker - 忽略 Service Worker 中的 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33832255/