myHotTake

How Do Service Workers Cache Assets Efficiently?

If you find this story helpful or entertaining, feel free to like or share it!


I’m a basketball coach, and my team is preparing for a big game. To ensure we’re ready, I carefully plan and organize our strategy. This is like setting up a Service Worker in JavaScript to cache assets. The Service Worker acts like my playbook, always ready to step in and execute the game plan.

First, I gather my team for a strategy session, which is akin to installing the Service Worker. During this phase, I lay out our tactics and make sure everyone knows their role. Similarly, during the Service Worker’s “install” event, I open up a cache and store all the crucial resources we’ll need for our game, just like caching assets like HTML, CSS, and JavaScript files.

As the game begins, I switch to the role of an active coach, ready to make quick decisions based on the flow of the game. This mirrors the “activate” event of a Service Worker, where it takes control and cleans up any old caches, ensuring that only the most up-to-date strategies are in play.

Now, as the game progresses, I watch from the sidelines, ready to provide guidance at a moment’s notice. This is akin to the Service Worker’s “fetch” event. When a player (or a browser request) needs something, I quickly check my playbook (the cache) to see if I already have a solution prepared. If I do, I call the play immediately, just as the Service Worker responds with cached assets. If not, I have to think on my feet and come up with a new strategy, similar to fetching data from the network.

Through careful preparation and quick responses, I ensure my team performs at their best, just as a Service Worker ensures a web app runs smoothly and efficiently. In both basketball and web development, having a solid strategy and a reliable cache can make all the difference in achieving victory.


We’re back at the strategy session, ready to set up our playbook. In JavaScript, this is done by listening for the “install” event of the Service Worker and then caching the necessary assets. Here’s how that looks in code:

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('my-cache').then(cache => {
      return cache.addAll([
        '/index.html',
        '/styles.css',
        '/script.js',
        '/images/logo.png'
      ]);
    })
  );
});

This snippet is like me gathering my team and making sure everyone knows their role. The addAll function is like detailing the specific plays and strategies — all the files my team needs to perform well.

Next, think about what happens when I’m actively coaching during the game. In the Service Worker, this is the “activate” event, which ensures old strategies (caches) are cleared out:

self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheName !== 'my-cache') {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

This code is like me ensuring our strategy is up-to-date, clearing out any old plays that might confuse my team.

Finally, during the game, I make quick decisions based on the current situation — just like the “fetch” event in the Service Worker:

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(response => {
      return response || fetch(event.request);
    })
  );
});

Here, I’m deciding whether to use a cached response (a play I’ve already prepared) or fetch a new one (come up with a new strategy). This ensures the team (or the web app) is always performing optimally.

Key Takeaways:

  • Preparation is Key: Just like a coach preparing for a game, setting up caching in the “install” phase ensures your app is ready with all necessary resources.
  • Stay Updated: The “activate” phase ensures only the latest strategies are in play, similar to clearing old caches.
  • Quick Decision Making: The “fetch” event allows for efficient resource retrieval, akin to a coach making real-time game decisions.