javascript – Caching resources from a CDN with sw-precache

Question:

I am trying to generate a service worker using sw-precache that should cache external resources. There are no problems with caching resources that lie next to it; this is done in this way:

gulp.task('generate-service-worker', ['copy-sw-scripts'], () => {
  const rootDir = 'dist';
  const filepath = path.join(rootDir, 'service-worker.js');

  return swPrecache.write(filepath, {
    cacheId: pkg.name || 'app',
    staticFileGlobs: [
      `${rootDir}/images/**/*`,
      `${rootDir}/fonts/**/*.woff2`,
      `${rootDir}/scripts/**/*.js`,
      `${rootDir}/styles/**/*.css`,
      `${rootDir}/*.{html,json}`
    ],
    stripPrefix: rootDir + '/'
  });
});

I try to generate a service worker that will cache external resources like this:

gulp.task('generate-service-worker', ['copy-sw-scripts'], () => {
  const rootDir = 'dist';
  const filepath = path.join(rootDir, 'service-worker.js');

  return swPrecache.write(filepath, {
    cacheId: pkg.name || 'app',
    importScripts: [
      'scripts/sw/sw-toolbox.js',
      'scripts/sw/runtime-caching.js'
    ],
    runtimeCaching: [
      {
        urlPattern: /^https:\/\/cdn\.mysite\.ua\/assets/,
        handler: 'networkFirst'
      }
    ],
    stripPrefix: rootDir + '/'
  });
});

But this does not bring the desired result. How to do it right?

I use sw-precache, sw-toolbox.

Answer:

Everything turned out to be quite simple, together with the dynamic caching of files from the CDN, it was also necessary to cache "local" files, this is how it works:

gulp.task('generate-service-worker', ['copy-sw-scripts'], () => {
  const rootDir = 'dist';
  const filepath = path.join(rootDir, 'service-worker.js');

  return swPrecache.write(filepath, {
    cacheId: pkg.name || 'app',
    importScripts: [
      'scripts/sw/sw-toolbox.js',
      'scripts/sw/runtime-caching.js'
    ],
    staticFileGlobs: [
      `${rootDir}/*.{html,json}`
    ],
    runtimeCaching: [
      {
        urlPattern: /^https:\/\/cdn\.mysite\.ua\/assets/,
        handler: 'networkFirst'
      }
    ],
    stripPrefix: rootDir + '/'
  });
});
Scroll to Top