【问题标题】:How to exclude url in workbox runtime caching?如何在工作箱运行时缓存中排除 url?
【发布时间】:2019-03-16 09:39:37
【问题描述】:

我在我的 django 项目中为 Gulp 使用 workbox-build。一切正常,但管理员网址存在一些问题。如我所见,/admin/* url 在运行时缓存 - 我可以在 Chrome DevTools/Application/Cache 中看到它们。如何从运行时缓存中排除管理员 URL?

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()
);

【问题讨论】:

  • 我在缓存 WordPress 管理资源时遇到了同样的问题。我最初为networkOnly()(使用自定义正则表达式)注册了一条路线,但被告知这不是一个好方法。我希望找到更好的选择。

标签: progressive-web-apps workbox


【解决方案1】:

Workbox的registerRoute()方法除了提供RegExps进行路由外,还支持matchCallback functions。我认为它们更容易理解,最近public documentation 中的大多数示例都已迁移到使用它们。

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()
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多