Created
April 26, 2017 17:19
-
-
Save renganatha10/78ae6eb64ade94b1c8b7106cdf0505a0 to your computer and use it in GitHub Desktop.
Basic service worker configuration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const CACHE_NAME = 'whatsappweb-cache-v9'; | |
const { assets } = global.serviceWorkerOption; | |
const urlsToCache = ['./', './index.html', ...assets]; | |
self.addEventListener('install', event => { | |
console.log('Service Woker Started'); | |
event.waitUntil( | |
caches.open(CACHE_NAME).then(cache => { | |
console.log('Opened cache'); | |
return cache.addAll(urlsToCache); | |
}) | |
); | |
}); | |
self.addEventListener('activate', event => { | |
console.log('Service Woker Activated'); | |
event.waitUntil( | |
caches.keys().then(cacheNames => | |
Promise.all( | |
cacheNames.map(thisCachenName => { | |
if (thisCachenName !== CACHE_NAME) { | |
return caches.delete(thisCachenName); | |
} | |
return caches; | |
}) | |
) | |
) | |
); | |
}); | |
self.addEventListener('fetch', e => { | |
e.respondWith( | |
caches | |
.match(e.request) | |
.then(response => { | |
if (response) { | |
return response; | |
} | |
const requestClone = e.request.clone(); | |
fetch(requestClone).then(response => { | |
if (!response) { | |
return response; | |
} | |
const responseClone = response.clone(); | |
caches.open(CACHE_NAME).then(cache => { | |
cache.put(e.request, responseClone); | |
return response; | |
}); | |
}); | |
}) | |
.catch(err => console.log('error while Service Woeker', err)) | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment