Cache-limiting in Service Workers …again

var trimCache = function (cacheName, maxItems) {
caches.open(cacheName)
.then(function (cache) {
cache.keys()
.then(function (keys) {
if (keys.length > maxItems) {
cache.delete(keys[0])
.then(trimCache(cacheName, maxItems));
}
});
});
};
window.addEventListener('load', function() {
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage({'command': 'trimCaches'});
}
});
self.addEventListener('message', function(event) {
if (event.data.command == 'trimCaches') {
trimCache(pagesCacheName, 35);
trimCache(imagesCacheName, 20);
}
});

--

--

A web developer and author living and working in Brighton, England. Everything I post on Medium is a copy — the originals are on my own website, adactio.com

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store