Skip to content

Instantly share code, notes, and snippets.

@renganatha10
Created April 26, 2017 17:19
Show Gist options
  • Save renganatha10/78ae6eb64ade94b1c8b7106cdf0505a0 to your computer and use it in GitHub Desktop.
Save renganatha10/78ae6eb64ade94b1c8b7106cdf0505a0 to your computer and use it in GitHub Desktop.
Basic service worker configuration
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