Checking for service worker updates in a single pa

2020-08-25 05:21发布

We have a signal page application that has Service worker installed and active.

Now our server rebuilds the app, Service worker file is being updated on the server side.

Our client has no idea about this new Service worker file and it is still using old Service worker file.

When It works? if I refresh/reload the app, new service worker is being installed .

How can we refresh the client if service worker file is being updated on the server and client is not being reloaded?

Possible solution: I think,I need to do the polling after 1 hour or something.

1条回答
爷、活的狠高调
2楼-- · 2020-08-25 06:22

Implicit updates

"The Service Worker Lifecycle" is a great resource for these types of questions.

In particular, there's a section dealing with updates:

An update is triggered:

  • On navigation to an in-scope page.
  • On functional events such as push and sync, unless there's been an update check within the previous 24 hours.
  • On calling .register() only if the service worker URL has changed.

Explicit updates

Because your SPA doesn't use real navigations, you won't get the automatic update checks mentioned in the first bullet point.

What you can do instead is follow the example from later on in that section:

As I mentioned earlier, the browser checks for updates automatically after navigations and functional events, but you can also trigger them manually:

navigator.serviceWorker.register('/sw.js').then(reg => {
  // sometime later…
  reg.update();
});

What I'd probably do is to modify your SPA's router and automatically make a call to reg.update() whenever your router is about to switch to a new view. That would simulate the same update-on-navigation behavior that you'd get in a non-SPA.

How does register() fit in?

After at least one call to navigator.serviceWorker.register() has been made, the service worker has a chance to install and activate. At this point, checks for service worker updates will happen irrespective of whether or not navigator.serviceWorker.register() is called again.

The earlier sections of this answer describe when these update checks will take place, either implicitly or explicitly.

You can dive into the details of this by comparing the differences between the Register and Update jobs in the service worker specification.

查看更多
登录 后发表回答