title: Cache-limiting in Service Workers
url: https://adactio.com/journal/9844
hash_url: dfe747a193bf51d2fa8680797ab29d7f

<p>When I was documenting <a href="https://adactio.com/journal/9775">my first Service Worker</a> I mentioned that every time a user requests a page, I store that page in a cache for later (offline) use:</p>

<blockquote>
  <p>Right now I’m stashing any HTML pages the user visits into the cache. I don’t think that will get out of control—I imagine most people only ever visit just a handful of pages on my site. But there’s the chance that the cache could get quite bloated. Ideally I’d have some way of keeping the cache nice and lean.</p>

  <p>I was thinking: maybe I should have a separate cache for HTML pages, and limit the number in that cache to, say, 20 or 30 items. Every time I push something new into that cache, I could pop the oldest item out.</p>

  <p>I could imagine doing something similar for images: keeping a cache of just the most recent 10 or 20.</p>
</blockquote>

<p>Well I&#8217;ve done that now. Here&#8217;s <a href="https://gist.github.com/adactio/4d588bb8a65fa11a3ea3">the updated Service Worker code</a>.</p>

<p>I&#8217;ve got a function in there called <code>stashInCache</code> that takes a few arguments: which cache to use, the maximum number of items that should be in there, the request (URL), and the response:</p>

<pre><code>var stashInCache = function(cacheName, maxItems, request, response) {
    caches.open(cacheName)
        .then(function (cache) {
            cache.keys()
                .then(function (keys) {
                    if (keys.length &lt; maxItems) {
                        cache.put(request, response);
                    } else {
                        cache.delete(keys[0])
                            .then(function() {
                                cache.put(request, response);
                            });
                    }
                })
        });
};
</code></pre>

<p>It looks to see if the current number of items in the cache is less than the specified maximum:</p>

<pre><code>if (keys.length &lt; maxItems)
</code></pre>

<p>If so, go ahead and cache the item:</p>

<pre><code>cache.put(request, response);
</code></pre>

<p>Otherwise, delete the first item from the cache and <em>then</em> put the item in the cache:</p>

<pre><code>cache.delete(keys[0])
  .then(function() {
    cache.put(request, response);
  });
</code></pre>

<p>For HTML requests, I limit the cache to 35 items:</p>

<pre><code>var copy = response.clone();
var cacheName = version + pagesCacheName;
var maxItems = 35;
stashInCache(cacheName, maxItems, request, copy);
return response;
</code></pre>

<p>For images, I&#8217;m limiting the cache to 20 items:</p>

<pre><code>var copy = response.clone();
var cacheName = version + imagesCacheName;
var maxItems = 20;
stashInCache(cacheName, maxItems, request, copy);
return response;
</code></pre>

<p>Here&#8217;s <a href="https://adactio.com/serviceworker.js">my updated Service Worker</a>.</p>

<p>The cache-limited seems to be working for pages. But for some reason the images cache has blown past its allotted maximum of 20 (you can see the items in the caches under the &#8220;Resources&#8221; tab in Chrome under &#8220;Cache Storage&#8221;).</p>

<p>This is almost certainly because I&#8217;m doing something wrong or have completely misunderstood how the caching works. If you can spot what I&#8217;m doing wrong, <a href="https://adactio.com/contact">please let me know</a>.</p>
