【问题标题】:Workbox service worker not storing images and API response in cacheWorkbox Service Worker 不在缓存中存储图像和 API 响应
【发布时间】:2019-05-31 02:03:29
【问题描述】:

我正在使用 Workbox Service Worker 来缓存图像和 API 响应,方法是为每个图像和 API 响应创建自定义缓存。虽然我可以看到路由匹配,但我看不到存储在缓存中的响应,然后由于缓存未命中,服务工作者正在从网络请求每个资源。

我已经为 service worker 使用了 workbox-webpack-plugin,并在其他文件中编写了自定义路由和缓存策略,然后将其传递给插件配置。

同样,我的 css 和 js 文件存储和服务都很好。

我尝试过使用不同的缓存策略,以及没有 webpack 插件的解决方法,但它们似乎都不起作用

//Cache JS files
    workbox.routing.registerRoute(
        new RegExp('.*\.js'),
        workbox.strategies.cacheFirst()
    );

//Cache API response
workbox.routing.registerRoute(
     new RegExp('\/api\/(xyz|abc|def)'),
         workbox.strategies.staleWhileRevalidate({
         cacheName: 'apiCache',
             plugins : [
                new workbox.expiration.Plugin({
                    maxEntries: 100,
                    maxAgeSeconds: 30 * 60 // 30 Minutes
                 })
            ]
    })
);

//cache images
workbox.routing.registerRoute(
    new RegExp('(png|gif|jpg|jpeg|svg)'),
    workbox.strategies.cacheFirst({
        cacheName: 'images',
        plugins: [
            new workbox.expiration.Plugin({
                maxEntries: 60,
                maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
            })
       ]
  })
);

这是 webpack 配置:

new workboxPlugin.InjectManifest({
    swSrc: 'customWorkbox.js',
    swDest: 'sw.js'
})

【问题讨论】:

    标签: service-worker workbox workbox-webpack-plugin


    【解决方案1】:

    根据workbox docs,外部 api 的正则表达式需要从一开始就匹配:

    Instead of matching against any part of the URL, the regular expression must match from the beginning of the URL in order to trigger a route when there's a cross-origin request.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多