Commit b45c1e5d authored by Julien Enselme's avatar Julien Enselme

Implement the network then cache strategy

If we don't have a response within 2s we get to the cache.
parent 270aca3f
......@@ -2,6 +2,8 @@ const VERSION = '{{ version }}';
const staticCachePrefix = 'static';
const staticCacheName = `${staticCachePrefix}-${VERSION}`;
const dynamicCacheName = 'dynamic';
// In milliseconds.
const networkWaitTime = 2000;
self.addEventListener('install', (event) => {
......@@ -27,14 +29,21 @@ self.addEventListener('fetch', (event) => {
}
event.respondWith(
getFromCache(event)
.then(
(response) => response,
() => tryToFetchAndSaveInCache(event, dynamicCacheName),
),
networkThenCache(event),
);
});
function networkThenCache(event) {
return Promise.race([
tryToFetchAndSaveInCache(event, dynamicCacheName),
new Promise((resolve, reject) => setTimeout(reject, networkWaitTime))
])
.then(
(response) => response,
() => getFromCache(event).catch(() => provideOfflineFallback(event))
);
}
function getFromCache(event) {
return caches.match(event.request)
.then((response) => {
......
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