Рассмотрим следующий код. Я разобью его на части:
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;
}
);
})
);
});
Здесь используется кэшированная первая стратегия, когда вы перезагружаете страницу, запускается событие извлечения.
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 (old ) уже присутствовал в кеше и отвечал им.