我正在尝试将服务工作者集成到我的应用程序中,但我发现即使在在线状态下,服务工作者也会尝试检索缓存的内容,但我希望在这些情况下它优先使用网络。我该怎么做?以下是我现在拥有的代码,但我不认为它正在起作用。为了简洁起见,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;
}
});
})
);
});
这似乎会导致类似于 The FetchEvent for "[url]" resulted in a network error response: an object that was not a Response was passed to respondWith().
的警告。我对服务工作者不太熟悉,因此对任何错误术语或不良实践表示歉意,欢迎任何建议。谢谢!