javascriptcachingservice-workercacheapi

Wildcards in ServiceWorker / Cache API


I am using ServiceWorker and in dev mode works perfectly, my problem is that in production mode my bundle name is generated using hash, e.g. 1234das3123ad5.bundle.js, so the service worker is not caching it. My sw code looks like:

self.addEventListener('install', function(event) {
  // pre cache a load of stuff:
  event.waitUntil(
    caches.open('mycache').then(function(cache) {
      return cache.addAll([
        '/dist/bundle.js',
        '/dist/app.css',
        '/dist/index.html',
        'https://cdnjs.cloudflare.com/ajax/libs/antd/2.7.2/antd.css'
      ]);
    })
  )
});

In the docs of Cache API I dont see any example on how I can achieve that.

Obviously I could cache everything under the dist folder, having something like:

self.addEventListener('install', function(event) {
  // pre cache a load of stuff:
  event.waitUntil(
    caches.open('mycache').then(function(cache) {
      return cache.addAll([
        '/dist/',
      ]);
    })
  )
});

But I dont find it an elegant, good in long term, solution. Is it a way to have wild cards in the Cache? Something like '/dist/*.bundle.js' ?


Solution

  • The web doesn't have the concept of folders, specifically there isn't a way for a browser to know all the valid URLs starting with a prefix.

    The rest of your site must be handling the URL changes for revisioning assets somehow, so why not use the same solution in your service worker?

    That's what I did for my blog - Django's static file manager adds the correct URLs https://jakearchibald.com/sw.js