【发布时间】:2018-01-19 00:20:26
【问题描述】:
在 Google 的一个 Service Worker 示例中,cache and return requests
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;
}
);
})
);
});
另一方面,MDN 提供的示例Using Service Workers 并没有克隆请求。
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');
})
);
});
因此,在 Google 示例中缓存未命中的情况下:
我明白为什么我们必须克隆响应:因为它已被cache.put 使用,我们仍然希望将响应返回给请求它的网页。
但是为什么必须克隆请求呢?在评论中它说它被 cache 和 用于获取的浏览器 消耗。究竟是什么意思?
- 请求流在缓存中的哪个位置被消耗?
cache.put?如果是,为什么caches.match不消费请求?
【问题讨论】: