我正在尝试将服务人员集成到我的应用程序中,但我发现服务人员即使在在线时也会尝试检索缓存的内容,但我希望它在这些情况下更喜欢网络。我怎样才能做到这一点?下面是我现在拥有的代码,但我不相信它正在工作。为简洁起见,省略了 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().
我是服务人员的新手,因此对任何错误的术语或不良做法表示歉意,欢迎任何提示。谢谢!