Service worker fetch all data

main.js

// Make Sure service work is supported
if('serviceWorker' in navigator){
console.log('Service work is supported');
window.addEventListener('load', ()=>{
navigator.serviceWorker.register('./sw_cached_pages_V2.js')
.then(reg =>console.log("Service Worker: Registered"))
.catch(err => console.log(`Service Worker: Error : ${err}`))
})
}

sw_cached_pages_V2.js

// Service Worker Fetch all data from sites

const cacheName = "v2";
// call install Events
self.addEventListener('install', function (event) {
});


// call Activate Events
self.addEventListener('activate', e => {
console.log("ServiceWorker: Activated");
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
console.log(cache);
if (cache !== cacheName) {
console.log("SeriveWorkder: Cleaning Old Caches")
return caches.delete(cache);
}
})
)
})
)
});

// Call Fetch Event
// Network falling back to the cache
self.addEventListener('fetch', e => {
console.log("ServiceWroker: Fetching");
e.respondWith(
fetch(e.request)
.then(res => {
// Make Copy/clone of response
const resClone = res.clone();
// Open cache
caches.open(cacheName)
.then(cache => {
// Add response to cache
cache.put(e.request, resClone);
})

return res;
}).catch(err => {
caches.match(e.request).then(res => res)
})

)
})

Comments

Popular posts from this blog

Module Bundel

Power of async and Promise