Workbox Examples: workbox-cache-expiration

When a maximum number of entries is given, the expiration performed using a least-recently used policy.

Responses fetched in this example are stored in a cache that imposes a maximum size of 2, and a maximum age of 10 seconds.

Messages

See more details by opening your browser's Developer Tools.

Explore the Code

JavaScript for Service Worker
importScripts('https://unpkg.com/workbox-cache-expiration@2.0.3/build/importScripts/workbox-cache-expiration.prod.v2.0.3.js');

const cacheName = 'cache-expiration-example';

// You can set maxEntries, maxAgeSeconds, or both.
const cacheExpiration = new workbox.cacheExpiration.CacheExpiration({
  maxEntries: 2,
  maxAgeSeconds: 10,
});

const testFileHandler = async (request) => {
  const networkResponse = await fetch(request);
  const cache = await caches.open(cacheName);

  // You **must** to call updateTimestamp() following each call to put() or
  // add(), or else CacheExpiration will not know what to expire.
  await cache.put(request, networkResponse.clone());
  await cacheExpiration.updateTimestamp({
    url: request.url,
    cacheName,
  });

  // Once the timestamps have been updated, call expireEntries() to actually
  // perform the cache cleanup. You can optionally wait for the cleanup to
  // complete before returning the response.
  await cacheExpiration.expireEntries({cacheName});

  return networkResponse;
};

/**
 * Set up a fetch handler that only responds to requests for .txt files.
 */
self.addEventListener('fetch', (event) => {
  if (event.request.url.endsWith('.txt')) {
    event.respondWith(testFileHandler(event.request));
  }
});

/**
 * This is boilerplate, instructing the service worker to take control as soon
 * as it can.
 */
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', () => self.clients.claim());
JavaScript for this Page
const buttons = document.querySelectorAll('button');
for (const button of [...buttons]) {
  button.addEventListener('click', async () => {
    const url = button.dataset.url;
    window.log('info', `Requesting ${url}...`);
    try {
      await fetch(button.dataset.url);
      window.log('info', '...request complete.'); 
    } catch (error) {
      window.log('warn', `...fetch failed due to '${error}'.`);
    }
    await window.logCachedFiles('cache-expiration-example');
  });
}