Search code examples
javascriptservice-workerprogressive-web-appssw-precachesw-toolbox

sw precache - runtime caching for assets loading from different domain


I am using sw precache to manage my service worker. Let us say my site is abc.com and the service worker is running on this site and loaded by url abc.com/service-worker.js

All the css and js are being loaded from different url for optimization purpose let us say xyz.com

Now in runtime cache when I provide

{
  // See https://github.com/GoogleChrome/sw-toolbox#methods
  urlPattern: '*.css',
  handler: 'fastest',
  // See https://github.com/GoogleChrome/sw-toolbox#options
  options: {
    cache: {
      maxEntries: 20,
      name: 'css-cache'
    }
  }
}

This caches css only from url abc.com/style/style.css and not xyz.com/style/test.css

I have tried

{
  // See https://github.com/GoogleChrome/sw-toolbox#methods
  urlPattern: 'https:\/\/xyz\.com\/*.js',
  handler: 'fastest',
  // See https://github.com/GoogleChrome/sw-toolbox#options
  options: {
    cache: {
      maxEntries: 20,
      name: 'js-cache'
    },
    // urlPattern: /\.googleapis\.com\//,
  }
}

but all in vain. If anyone has faced the same issue ever any help in the correct direction will be highly appreciated.


Solution

  • I believe your problem is that you pass a string as urlPattern when you should actually pass a regular expression.

    So instead of 'https:\/\/xyz\.com\/*.js' you should use /https:\/\/xyz\.com\/*.js/.