考虑以下代码。我将把它分成几部分:
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request).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;
}
);
})
);
});
这里使用的是缓存优先策略,每当你重新加载页面时,就会触发一个 fetch 事件。
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
首先它检查所需的请求是否在缓存中可用,如果是则它将返回响应并且不会从网络获取。
return fetch(event.request).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;
}
);
})
);
现在,如果文件不存在于缓存中,则此块会进入网络收集所需的文件,然后对其进行响应,并将其保存到缓存中以供进一步使用。
假设您有一个文件 sample.html 并且它已被缓存,现在您对文件的代码进行了一些更改,但这些更改不会在您的浏览器上看到,因为它会看到 sample.html(旧) 已经存在于缓存中并用它来响应。