Consider the following code.I will break it in parts:
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;
}
);
})
);
});
Over here cached first strategy is used,whenever you reload the page a fetch event is triggered.
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
First it checks if the required request is available in the cache,if yes then it will return the response and won't fetch from network.
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;
}
);
})
);
Now if the file was not present in the cache then this block gets to network gathers the required files then respond with it an also save it to cache for further use.
Consider the case that you have a file sample.html and it is cached,now you make some changes to the file's code but the changes won't be seen on your browser because it will see that the sample.html(old) was already present in the cache and respond with it.