Caching Url without explicit declaration in dynamicUrlToDependencies using sw-precache

164 Views Asked by At

Is there a way, using sw-precache, to cache the url you are currently on without exactly specifying the url string in dynamicUrlToDependencies? My page caches when I supply a specific relative url /dynamic/url-circle, but not if I supply just /. I'm assuming this happens because my url is http://localhost:3000/dynamic/url-circle, and not just http://localhost:3000/. I would need this to work for any url string as I would not know the exact url after dynamic/ (ex. /dynamic/url-triangle, /dynamic/url-square). Are there any abstractions or a string patterns to use for dynamicUrlToDependencies? Or is there a different solution I can use?

ex:

    dynamicUrlToDependencies: {
       '/dynamic/url-circle': [ 'public/dist/css/dynamic.css', 'public/dist/js/dynamic.js' ],
       '/': [ 'public/dist/css/dynamic.css', 'public/dist/js/dynamic.js' ],
  },

Here is are my sw-precache settings in my Gruntfile:

   const rootDir = 'public'

   const config = {
       cacheId: version,
       handleFetch: true,
       logger: grunt.log.writeln,
       staticFileGlobs: [
         `${rootDir}/dist/js/*.{css,js}`,
         `${rootDir}/dist/css/*.{css,js}`,
         `${rootDir}/dist/offline.html`,
       ],
       dynamicUrlToDependencies: {
          '/dynamic/url-circle': [ 'public/dist/css/dynamic.css', 'public/dist/js/dynamic.js' ],
          '/': [ 'public/dist/css/dynamic.css', 'public/dist/js/dynamic.js' ],
       },
       stripPrefix: `${rootDir}/`,
       directoryIndex: 'dist/offline.html',
       navigateFallback: 'dist/offline.html',
       verbose: true,
       maximumFileSizeToCacheInBytes: 15 * 1024 * 1024, // 15MB
   };
1

There are 1 best solutions below

0
On

You can use runtimeCaching to cache your page. I did something like this.

  runtimeCaching: [
      urlPattern: /\/url-lot\//,
      handler: 'networkFirst',
    },
  ]

and then every url with url-lot in it would be cached. Feels a bit obvious now, but that's life.