Re: [w3c/ServiceWorker] Provide a one-line way to listen for a waiting Service Worker (#1222)

A few points.

> Since this is related to the registration, this promise should really go on the registration. That way it can be used on all the origin's registrations.

I worry that this solves non-problems without adequately addressing the real use case: refresh banners.

I claim that the _only_ use case for this is a refresh banner. I'm not aware of any use case where someone would want to track state changes on all of the origin's registrations; the only registration that matters for refresh banners is the registration for the current page's controller.

My goal is to listen for a refresh banner in one easy line. A successful implementation should make us want to delete an entire quiz from the Udacity course on service workers. There's already an "easy" solution in nine lines of boilerplate; anything that makes the use case just slightly more convenient is probably not worth the trouble, IMO.

Under Jake's proposal, the whole code snippet would look like this. (Note that it has to be in ES5, since it's going to run in the client-side page.

```js
navigator.serviceWorker.ready.then(function(reg) {
  if (reg.waiting) return alertUser(reg);
  return reg.on('statechange').filter(function(e) {
    return e.target.state === 'installed';
  }).first().then(function(e) {
    alertUser(reg);
  });
})
```

IMO, the observable didn't even help; it's actually a bit easier to just use `addEventListener`.

```js
navigator.serviceWorker.ready.then(function(reg) {
  if (reg.waiting) return alertUser(reg);
  return reg.addEventListener('statechange', function(e) {
    if (e.target.state === 'installed') alertUser(reg);
  });
})
```

This is an improvement over the status quo, but the cow path is only half paved. It has to repeat `alertUser(reg)`, which means that `alertUser` has to be a separate, named function. A `.waiting` promise would be simpler and DRYer.

```js
navigator.serviceWorker.waiting.then(alertUser);
```

Being DRY allows users to define the `alertUser` function inline:

```js
navigator.serviceWorker.waiting.then(function(reg) {
  var button = document.createElement('button');
  button.textContent = 'This site has updated. Please click here to see changes.');
  button.style.position = 'fixed';
  button.style.bottom = '24px';
  button.style.left = '24px';
 
  button.addEventListener('click', function() {
    if (reg.waiting) {
      button.disabled = true;
      reg.waiting.postMessage('skipWaiting');
    }
  });
  document.body.appendChild(button);
});
```

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/1222#issuecomment-351752828

Received on Thursday, 14 December 2017 15:59:47 UTC