如何判断等待的服务人员是否准备就绪?

时间:2018-11-05 08:00:23

标签: javascript service-worker service-worker-events

According to the specServiceWorker.waiting属性返回对已安装并等待激活的服务工作者的引用。

很好。但是,如何确定等待服务的工作人员何时过渡到新状态?

ServiceWorker.waiting返回的服务工作者似乎没有任何必要的事件来通知状态更改:

if (registration.waiting) {

  registration.waiting.postMessage('skip-waiting');

  // This is failing because ready is undefined.
  registration.waiting.ready.then(function () {

    console.log('new service worker - ready');
 }
}

1 个答案:

答案 0 :(得分:0)

在撰写本文时,registration.waiting.onstatechange在Chrome中为空。但是,可以进行以下操作:

if (registration.waiting) {

  const waiting = registration.waiting;

  waiting.postMessage('skip-waiting');

  waiting.addEventListener('statechange', function (e) {

    if(waiting.state === 'activated') {
      console.log('new service worker - ready');
    }
 }
}