Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Properly wait for the serviceworker to be ready #6

Open
t-mullen opened this issue Dec 16, 2017 · 2 comments
Open

Properly wait for the serviceworker to be ready #6

t-mullen opened this issue Dec 16, 2017 · 2 comments

Comments

@t-mullen
Copy link

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
Copy link
Author

From the discussion in w3c/ServiceWorker#799

@Mistifiou
Copy link

Mistifiou commented Apr 10, 2018

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)
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants