browser-server icon indicating copy to clipboard operation
browser-server copied to clipboard

Properly wait for the serviceworker to be ready

Open t-mullen opened this issue 6 years ago • 2 comments

It seems that there is a small wait between when the .ready method is called and the serviceworker actually claims the client.

We should wait for the controller before firing ready:

  navigator.serviceWorker.register('/worker.js').then(function () {
    return navigator.serviceWorker.ready
  }).then(function (reg) {
    if (navigator.serviceWorker.controller) {
      self.emit('ready')
    } else {
      var listener = navigator.serviceWorker.addEventListener('controllerchange', () => {
        navigator.serviceWorker.removeEventListener('controllerchange', listener)
        self.emit('ready')
      })
    }
  })

t-mullen avatar Dec 16 '17 20:12 t-mullen

From the discussion in https://github.com/w3c/ServiceWorker/issues/799

t-mullen avatar Dec 16 '17 20:12 t-mullen

Seems like addEventListener return is void. I'm currently using another method, that "handle" hard reload by rejecting promise.

private resolveControllerReady(resolve, reject, count: number = 0) {
  count++;
  if(count > 10) {
    reject(`Controller still not ready after (${count}) attempts`);
  } else {
    if (navigator.serviceWorker.controller) {
      console.info(`Controller ready after (${count}) attempt(s)`);
      resolve ();
    } else {
      console.warn(`Controller is not ready yet ! waiting ... - (${count})`);
      return setTimeout(()=>{
        this.resolveControllerReady(resolve, reject, count);
      }, 2000)
    }
  }
}

Mistifiou avatar Apr 10 '18 10:04 Mistifiou