Cache-limiting in Service Workers …again

var trimCache = function (cacheName, maxItems) {
.then(function (cache) {
.then(function (keys) {
if (keys.length > maxItems) {
.then(trimCache(cacheName, maxItems));
window.addEventListener('load', function() {
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage({'command': 'trimCaches'});
self.addEventListener('message', function(event) {
if ( == '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,

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