Cache-limiting in Service Workers

var stashInCache = function(cacheName, maxItems, request, response) {
caches.open(cacheName)
.then(function (cache) {
cache.keys()
.then(function (keys) {
if (keys.length < maxItems) {
cache.put(request, response);
} else {
cache.delete(keys[0])
.then(function() {
cache.put(request, response);
});
}
})
});
};
if (keys.length < maxItems)
cache.put(request, response);
cache.delete(keys[0])
.then(function() {
cache.put(request, response);
});
var copy = response.clone();
var cacheName = version + pagesCacheName;
var maxItems = 35;
stashInCache(cacheName, maxItems, request, copy);
return response;
var copy = response.clone();
var cacheName = version + imagesCacheName;
var maxItems = 20;
stashInCache(cacheName, maxItems, request, copy);
return response;

--

--

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