Commit b3b6e5d3 authored by Julien Enselme's avatar Julien Enselme

Can serve dynamic requests from the cache

parent 9594eac5
const VERSION = '1.0.0';
const staticCachePrefix = 'static';
const staticCacheName = `${staticCachePrefix}-${VERSION}`;
const dynamicCacheName = 'dynamic';
self.addEventListener('install', (event) => {
......@@ -10,6 +11,7 @@ self.addEventListener('install', (event) => {
.then(cache => {
console.log('[SW] Caching app shell');
cache.addAll([
'/static/manifest.json',
'/',
'/offline/',
]);
......@@ -27,9 +29,25 @@ self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then((response) => {
console.log(`[SW] Requesting ${event.request.url}.`)
// If we have the response in the cache, we return it.
// If not, we try to fetch it.
return response || fetch(event.request);
if (response) {
console.log(`[SW] Served response to ${event.request.url} from the cache.`);
return response;
}
return fetch(event.request)
.then(res => {
return caches.open(dynamicCacheName)
.then(cache => {
// We can read a response only once. So if we don't clone it here,
// we won't be able to see anything in the browser.
cache.put(event.request.url, res.clone());
return res;
})
})
.catch(err => console.warn('Warning: app is offline', err));;
}),
);
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment