【问题标题】:Issue with workbox 2.1.0 precaching工作箱 2.1.0 预缓存问题
【发布时间】:2017-12-05 11:39:32
【问题描述】:

我正在使用 workbox 2.1.0 来生成 service worker,并且需要从服务器的资产目录(比如 index.html 和 clear.png)和 CDN 中的一个文件(比如 https://akamai.com/dummy/path/app.js)预缓存一些文件。 我正在使用 gulp 进行构建。代码是这样的

gulp.task('sw', () => {
      return wbBuild.generateSW({
          globDirectory: '.',
          swDest: 'sw_gulp_generated.js',
          staticFileGlobs: [
              'index.html',
              'clear.png'
              ],          
          verbose: true,
  })
      .then(() => {
        console.log('Service worker generated.');
      })
      .catch((err) => {
        console.log('[ERROR] This happened: ' + err);
      });
    });

所以,这工作正常,并且生成的服务工作者在预缓存列表中都有这两个文件,这里是:

const fileManifest = [
  {
    "url": "index.html",
    "revision": "b6eb7cd7599ed6584a715cdfc75a81c0"
  },
  {
    "url": "clear.png",
    "revision": "e17de36d2c2ddf7b068892fa4678cd31"
  },

];
const workboxSW = new self.WorkboxSW();
workboxSW.precache(fileManifest);
//more code follows ...

我测试过,效果很好

现在,问题是:如何在预缓存列表中添加第三个资产 (https://akamai.com/dummy/path/app.js)。我试着把它放在staticFileGlobs,但它错误地说:

One of the glob patterns doesn't match any files

显然是因为它试图在globDirectory 中查找文件https://akamai.com/dummy/path/app.js 却找不到。

那么,基本上,如何在使用 gulp(或任何构建工具)时将 CDN URL 注入到生成的服务工作者的预缓存列表中?

【问题讨论】:

  • 我尝试编辑生成的 Service Worker 以将 akamai.com/dummy/path/app.js 包含在预缓存列表中,并且它工作了 const fileManifest = [ { "url": "index.html", "revision": "b6eb7cd7599ed6584a715cdfc75a81c0" }, { "url": "https://akamai.com/dummy/path/app.js", "revision": "577cd1b1345e3676cc5a4e2acce85191" }, { "url": "clear.png", "revision": "e17de36d2c2ddf7b068892fa4678cd31" } ]; const workboxSW = new self.WorkboxSW(); workboxSW.precache(fileManifest); 问题仍然是在 Gulp 的构建过程中如何实现它?

标签: gulp progressive-web-apps workbox


【解决方案1】:

看起来generateSW 不接受自定义precache 规则。不过,您可以传递 runtimeCaching 选项。如果客户端请求第三方文件,它只会缓存它们。由于是第三方请求,如果请求导致错误响应,错误响应将被缓存并not updated

wbBuild.generateSW({
  globDirectory: '.',
  swDest: 'sw_gulp_generated.js',
  staticFileGlobs: [
    'index.html',
    'clear.png'
  ],          
  verbose: true,
  runtimeCaching: [{
    urlPattern: 'https://exapmle.com/file.min.js',
    handler: 'staleWhileRevalidate',
    options: {
      cacheableResponse: {
        statuses: [0],
      },
    },
  }]
})

【讨论】:

  • 感谢您的回复,我认为这会起作用,但 app.js 位于 webApp 的关键渲染路径中,因此我认为将其预先缓存是理想的。尽管如此,由于我们对 wbBuild 的限制,我想我现在可能需要使用 runtimeCaching。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
相关资源
最近更新 更多