lib*_*ked 9 javascript service-worker
在Google的一个Service Worker示例中,缓存和返回请求
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
// IMPORTANT: Clone the request. A request is a stream and
// can only be consumed once. Since we are consuming this
// once by cache and once by the browser for fetch, we need
// to clone the response.
var fetchRequest = event.request.clone();
return fetch(fetchRequest).then(
function(response) {
// Check if we received a valid response
if(!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// IMPORTANT: Clone the response. A response is a stream
// and because we want the browser to consume the response
// as well as the cache consuming the response, we need
// to clone it so we have two streams.
var responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(event.request, responseToCache);
});
return response;
}
);
})
);
});
Run Code Online (Sandbox Code Playgroud)
另一方面,MDN(使用服务工作者)提供的示例不会克隆请求.
this.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(resp) {
return resp || fetch(event.request).then(function(response) {
caches.open('v1').then(function(cache) {
cache.put(event.request, response.clone());
});
return response;
});
}).catch(function() {
return caches.match('/sw-test/gallery/myLittleVader.jpg');
})
);
});
Run Code Online (Sandbox Code Playgroud)
因此,对于Google示例中的缓存未命中情况:
我理解为什么我们必须克隆响应:因为它被消耗了cache.put,我们仍然希望将响应返回给请求它的网页.
但为什么要克隆请求呢?在评论中,它表示它被缓存和浏览器用于获取.这究竟是什么意思?
cache.put?如果是这样,为什么不caches.match消耗请求?在我看来,评论很清楚地说明了为什么该代码的作者认为克隆是必要的:
一个请求是一个流,只能被消费一次。由于我们一次通过缓存使用它,一次由浏览器用于获取,我们需要克隆响应。
请记住,body请求的 可以是ReadableStream。如果cache.match必须读取流(或部分读取流)以了解缓存条目是否匹配,则后续读取fetch将继续读取,而丢失读取的任何数据cache.match。
如果它只在有限的情况下重要(除非 Google 示例中的代码完全错误并且没有必要),我不会感到惊讶,因此如果不这样做可能在许多测试用例中都有效(例如,body是null或字符串,而不是流)。请记住,MDN 非常好,但它是社区编辑的,错误和糟糕的示例确实会定期出现。(多年来,我不得不修复其中的几个明显错误。)通常社区会发现它们并修复它们。
| 归档时间: |
|
| 查看次数: |
1637 次 |
| 最近记录: |