Caching using Service worker
console.log("SW startup...");
let cacheName = 'Akkis_First_Cache-v3',
assetsToCache = [
'/',
'/index.html',
'/index.js',
'/jquery-1.11.3.min.js'
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(cacheName)
.then((cache) => {
return cache.addAll(assetsToCache);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(name) {
return name.startsWith('Akkis_') && name !== cacheName;
})
.map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
});
/*self.addEventListener('fetch', (event) => {
console.log(event.request);
event.respondWith(
caches.match(event.request)
.then((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 2 stream.
var responseToCache = response.clone();
caches.open(cacheName)
.then(function(cache) {
cache.put(event.request, responseToCache);
});
return response;
}
);
})
);
});
self.addEventListener('activate', function(event) {
console.log("SW activated");
});*/