在单页应用中检查 Service Worker 更新 [英] Checking for service worker updates in a single page app

查看:77
本文介绍了在单页应用中检查 Service Worker 更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个安装了 Service Worker 并处于活动状态的信号页面应用程序.

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

现在我们的服务器重建了应用程序,Service Worker 文件正在服务器端更新.

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

我们的客户不知道这个新的 Service Worker 文件,它仍在使用旧的 Service Worker 文件.

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

何时有效?如果我刷新/重新加载应用程序,则正在安装新的 Service Worker.

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

如果服务器上的 Service Worker 文件正在更新并且客户端没有重新加载,我们如何刷新客户端?

可能的解决方案:我想,我需要在 1 小时左右后进行投票.

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

推荐答案

隐式更新

Service Worker 生命周期"是一个很好的资源对于这些类型的问题.

Implicit updates

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

特别是,有一个部分处理更新:

触发更新:

  • 导航到范围内的页面.
  • 对于推送和同步等功能事件,除非在过去 24 小时内进行了更新检查.
  • 仅当 Service Worker URL 已更改时才调用 .register().

显式更新

由于您的 SPA 不使用真正的导航,您将无法获得第一个要点中提到的自动更新检查.

Explicit updates

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

您可以做的是遵循 稍后的示例在该部分:

正如我之前提到的,浏览器会自动检查更新在导航和功能事件之后,但您也可以触发它们手动:

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

我可能要做的是修改您的 SPA 的路由器,并在您的路由器即将切换到新视图时自动调用 reg.update().这将模拟您在非 SPA 中获得的相同导航更新行为.

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.

至少调用一次 navigator.serviceWorker.register() 后,Service Worker 就有机会安装和激活.此时,无论 navigator.serviceWorker.register() 是否再次被调用,都会检查 Service Worker 更新.

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.

您可以通过比较注册更新 service worker 规范中的作业.

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

这篇关于在单页应用中检查 Service Worker 更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆