Cache Expiration Demo

Background

The service worker in this example demonstrates using the maxCacheEntries and maxCacheAgeSeconds options. It uses a dedicated cache to hold YouTube video thumbnails. That dedicated cache will purge entries once they're older than 30 seconds, and store at most 10 entries. It uses the cacheFirst strategy, so any responses that are still in the cache will be used directly, without going against the network.

While this example uses both maxCacheEntries and maxCacheAgeSeconds, it's possible to use each of those options independently.

The cache used for YouTube thumbnail URLs is separate from the "default" cache, which is used for all other requests, like YouTube API responses and this page's CSS, JavaScript, and HTML. The page doesn't impose any upper limit on the size of that default cache, and we can use a networkFirst strategy for it.

Creating a dedicated cache with expiration options for dynamic, unbounded requests is a useful pattern to follow. If we just used the default cache without imposing a cache expiration, then that cache would grow in size as more and more searches were performed, needlessly consuming disk space for old thumbnails that are likely no longer needed.

Live Demo

Try increasing the number of thumbnails returned, or changing the search term, and then observe the cache expirations logged in the developer console.