ServiceWorkerContainer.ready 用于特定的脚本 URL? [英] ServiceWorkerContainer.ready for a specific scriptURL?

查看:41
本文介绍了ServiceWorkerContainer.ready 用于特定的脚本 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ServiceWorkerContainer.ready 解析为活动的 ServiceWorkerRegistration,但如果有多个服务工作人员在运行(例如来自先前页面加载的服务工作人员,同一页面内的多个注册),则可以解析为多个服务工作人员.当执行一段代码时,如何确保特定的 Service Worker 正在处理网络事件?

ServiceWorkerContainer.ready resolves to an active ServiceWorkerRegistration, but if there are multiple service workers in play (e.g. service workers from previous page loads, multiple registrations within the same page) there are multiple service workers it could resolve to. How can I make sure that a particular service worker is handling network events when a chunk of code is executed?

即如何写一个函数registerReady(scriptURL, options),可以使用如下:

That is, how can I write a function registerReady(scriptURL, options) that can be used as follows:

registerReady("foo.js").then(function (r) {
    // "foo.js" is active and r.active === navigator.serviceWorker.controller
    fetch("/"); // uses foo.js's "fetch" handler
});

registerReady("bar.js").then(function (r) {
    // "bar.js" is active and r.active === navigator.serviceWorker.controller
    fetch("/"); // use bar.js's "fetch" handler
});

推荐答案

首先,请注意每个范围只能有一个活动的 Service Worker,并且您的客户端页面最多只能由一个 Service Worker 控制.因此,当 ready 解析时,您肯定知道控制您的页面的服务工作者处于活动状态.

First, notice there can be only one active service worker per scope and your client page can be controlled by at most one and only one service worker. So, when ready resolves, you know for sure the service worker controlling your page is active.

要知道 任意 sw 是否处于活动状态,您可以注册它并检查注册中的 Service Worker 队列并监听其状态的变化.例如:

To know if an arbitrary sw is active you can register it and check the queue of service workers in the registration and listen for changes in their state. For instance:

function registerReady(swScript, options) {
  return navigator.serviceWorker.register(swScript, options)
  .then(reg => {
    // If there is an active worker and nothing incoming, we are done.
    var incomingSw = reg.installing || reg.waiting;
    if (reg.active && !incomingSw) {
      return Promise.resolve();
    }

    // If not, wait for the newest service worker to become activated.
    return new Promise(fulfill => {
      incomingSw.onstatechange = evt => {
        if (evt.target.state === 'activated') {
          incomingSw.onstatechange = null;
          return fulfill();
        }
      };
    });
  })
}

希望对你有意义.

这篇关于ServiceWorkerContainer.ready 用于特定的脚本 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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