How to exclude url in workbox runtime caching?
Asked Answered
A

1

6

I am using workbox-build for Gulp in my django project. All works correct, but there are some problems with admin urls. As I see, /admin/* urls caching in runtimes - I can see them in Chrome DevTools/Application/Cache. How can I exclude admin urls from runtime caching?

gulp.js:

gulp.task('service-worker', () => {
   return workboxBuild.injectManifest({
         globDirectory: '/var/www/example.com/',
         swSrc:  '/var/www/example.com/core/templates/core/serviceWorker/sw-dev.js',
         swDest: '/var/www/example.com/core/templates/core/serviceWorker/sw.js',
         globPatterns:['**/*.{html,js,css,jpg,png,ttf,otf}'],
         globIgnores: ['admin\/**','media\/**','core\/**','static/admin\/**','static/core/scripts/plugins/**']
         }).then(({count, size, warnings}) => {
         });

sw.js:

importScripts("https://storage.googleapis.com/workbox- cdn/releases/3.4.1/workbox-sw.js");
workbox.precaching.precacheAndRoute([]);
workbox.googleAnalytics.initialize();
workbox.routing.registerRoute(
workbox.strategies.cacheFirst({
// Use a custom cache name
cacheName: 'image-cache',
plugins: [
  new workbox.expiration.Plugin({
    // Cache only 20 images
    maxEntries: 30,
    // Cache for a maximum of a week
    maxAgeSeconds: 7 * 24 * 60 * 60,
    })
   ],
  })
);

workbox.routing.registerRoute(
    /.*\.(?:ttf|otf)/,
    workbox.strategies.cacheFirst({
    cacheName: 'font-cache',
    })
);

workbox.routing.registerRoute(
  new RegExp('\/$'),
  workbox.strategies.staleWhileRevalidate()
);

workbox.routing.registerRoute(
  new RegExp('contacts\/$'),
  workbox.strategies.staleWhileRevalidate()
);
workbox.routing.registerRoute(
  new RegExp('pricelist\/$'),
  workbox.strategies.staleWhileRevalidate()
);
Antaeus answered 16/3, 2019 at 9:39 Comment(1)
I'm having this same issue with caching WordPress admin resources. I initially registered a route specifically for networkOnly() (with a custom regex) but have been told that is not a good way to do it. I'm hoping to find a better alternative.Semiconductor
K
1

In addition to providing RegExps for routing, Workbox's registerRoute() method supports matchCallback functions. I think that they're easier to make sense of, and recently most of the examples in the public documentation have migrated to use them.

workbox.routing.registerRoute(
  // Match all navigation requests, except those for URLs whose
  // path starts with '/admin/'
  ({request, url}) => request.mode === 'navigate' &&
                      !url.pathname.startsWith('/admin/'),
  new workbox.strategies.StaleWhileRevalidate()
);
Keciakeck answered 15/12, 2020 at 18:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.