Commit c81e1288 authored by Julien Enselme's avatar Julien Enselme

Clean dynamic cache

parent 98d0a966
......@@ -8,6 +8,8 @@ const appShell = [
'',
'offline/',
].map((partialUrl) => `${location.protocol}//${location.host}/${partialUrl}`);
const maxNumberItemsDynamicCache = 5;
const urlsToCacheTimes = new Map();
// In milliseconds.
const networkWaitTime = 2000;
......@@ -103,13 +105,49 @@ function fetchAndSaveInCache(event, cacheName) {
.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.
console.log('[SW] Saving in the cache.');
cache.put(event.request.url, res.clone());
cache.put(event.request.url, res.clone())
.then(() => {
urlsToCacheTimes.set(event.request.url, Date.now());
return trimCache(cache, maxNumberItemsDynamicCache, urlsToCacheTimes);
});
return res;
});
});
}
function trimCache(cache, maxItems, cacheTimeInfos) {
if (cacheTimeInfos.size <= maxItems) {
console.log('[SW] Nothing to trim from the cache.');
return Promise.resolve();
}
// We sort all entries by descending dates.
// We keep a slice of the maxItems more recent items.
const urlsToKeep = Array.from(cacheTimeInfos.entries())
.sort((a, b) => a[1] - b[1])
.reverse()
.slice(0, maxItems)
.map(([url, _]) => url);
console.log('[SW] Keeping in cache', urlsToKeep);
return cache.keys()
.then((keys) => {
const deletions = keys.map(key => {
if (urlsToKeep.includes(key.url)) {
return Promise.resolve();
}
console.log(`[SW] Removing ${key.url} from the cache.`);
cacheTimeInfos.delete(key.url);
return cache.delete(key);
});
return Promise.all(deletions);
})
.then(() => console.log('[SW] Done trimming cache.'))
.catch(() => console.log('[SW] Error while trimming cache.'));
}
function provideOfflineFallback(event) {
return caches.open(staticCacheName)
.then((cache) => {
......
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