Awo*_*wol 5 javascript caching promise service-worker
我在 chrome 上使用 service worker 来缓存网络响应。当客户请求资源时我打算做什么:
检查缓存 - 如果存在,从缓存返回,但如果文件与缓存版本不同,也会向服务器发送请求并更新缓存。如果缓存没有它,向服务器发送一个请求,然后缓存响应。
这是我当前用于执行相同操作的代码:
self.addEventListener('fetch', function (event) {
var requestURL = new URL(event.request.url);
var freshResource = fetch(event.request).then(function (response) {
if (response.ok && requestURL.origin === location.origin) {
// All good? Update the cache with the network response
caches.open(CACHE_NAME).then(function (cache) {
cache.put(event.request, response);
});
}
// Return the clone as the response would be consumed while caching it
return response.clone();
});
var cachedResource = caches.open(CACHE_NAME).then(function (cache) {
return cache.match(event.request);
});
event.respondWith(cachedResource.catch(function () {
return freshResource;
}));
});
Run Code Online (Sandbox Code Playgroud)
此代码不起作用,因为它会引发错误:
url的 FetchEvent导致网络错误响应:一个不是 Response 的对象被传递给 respondWith()。
任何人都可以指出我正确的方向吗?
好吧,在人们指出建议(谢谢你)并找到解决方案后,我摆弄了代码。
self.addEventListener('fetch', function (event) {
var requestURL = new URL(event.request.url);
var freshResource = fetch(event.request).then(function (response) {
var clonedResponse = response.clone();
// Don't update the cache with error pages!
if (response.ok) {
// All good? Update the cache with the network response
caches.open(CACHE_NAME).then(function (cache) {
cache.put(event.request, clonedResponse);
});
}
return response;
});
var cachedResource = caches.open(CACHE_NAME).then(function (cache) {
return cache.match(event.request).then(function(response) {
return response || freshResource;
});
}).catch(function (e) {
return freshResource;
});
event.respondWith(cachedResource);
});
Run Code Online (Sandbox Code Playgroud)
整个问题源于缓存中不存在该项目并cache.match返回错误的情况。在这种情况下,我需要做的就是获取实际的网络响应(注意return response || freshResource)
这个答案Aha!对我来说是一个时刻(尽管实现不同):
Use ServiceWorker cache only when offline