Workbox SW:运行时缓存在第二次重新加载之前无法正常工作

时间:2018-04-18 10:18:52

标签: caching progressive-web-apps workbox

我是服务工作者和工作箱的新手。我目前正在使用工作箱来预处理我的静态资源文件,这很好,我希望我的其他第三方URL在运行时也会被缓存,但是直到我第二次重新加载到页面上才能工作:(

如下所示是我的服务工作者代码的副本,请注意我故意将原始链接替换为abc.domain.com:)

workbox.routing.registerRoute(
  //get resources from any abc.domain.com/
  new RegExp('^https://abc.(?:domain).com/(.*)'),
  /*
  *respond with a cached response if available, falling back to the network request if it’s not cached. 
  *The network request is then used to update the cache.
  */
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'Bill Resources',
    maxEntries: 60,
    maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
  }),
); 

workbox.routing.registerRoute(
  new RegExp('^https://fonts.(?:googleapis|gstatic).com/(.*)'),
  //serve from network first, if not availabe then cache
  workbox.strategies.networkFirst(),
); 

workbox.routing.registerRoute(
  new RegExp('^https://use.(?:fontawesome).com/(.*)'),
  //serve from network first, if not availabe then cache
  workbox.strategies.networkFirst(),
); 

我已经清除了无数的存储时间,我从谷歌开发者工具刷新了缓存存储,但似乎都是一样的。自定义链接,google字体和fontawesome中的资源无法在第一次缓存。下面是控制台和我的页面的缓存存储选项卡第一次加载图像和第二次加载图像。

First Load Second Load

请不要知道我做错了什么以及为什么会这样。

先谢谢

2 个答案:

答案 0 :(得分:1)

This is expected behaviour.

The way service workers get set up is that they will have an install and activate phase, where installation can happen when ever a new service worker is registered or a service worker updates.

A service worker will then activate when it's safe to do so (i.e. no windows are currently being "controlled" be a service worker).

Once a service worker is activated, it'll control any new pages.

What you are seeing is:

  1. Page is loaded and the page registers a service worker
  2. The service worker precaches any files during it's install phase
  3. A service activates but isn't controlling any pages
  4. You refresh the page and at this point the page is controlled and requests will go through the service worker (resulting in the caching on the second load).

答案 1 :(得分:0)

服务启动器不会激活任何内容。它仅在第二次命中时被激活。要在第一次命中时实现缓存,您必须指导服务人员跳过等待激活的过程。您可以通过

    self.addEventListener('install', () => {
            self.skipWaiting(); //tells service worker to skip installing and activate it
            /*your code for pre-caching*/
    });

一旦被跳过,它将进入激活模式并等待缓存,但不会缓存客户端交互。为此,请应用以下行

    self.addEventListener('activate', () => {
        clients.claim();
    });

它将在第一次匹配时开始缓存