究竟是什么触发了这个 Service Worker 代码的运行?

New*_*eX2 2 javascript service-worker

Create-react-app 附带一个 registerServiceWorker.js 文件,其中包含注册服务工作者的代码。我只是有点困惑它是如何工作的。有问题的代码是:

function registerValidSW(swUrl) {
  navigator.serviceWorker
    .register(swUrl)
        .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the old content will have been purged and
              // the fresh content will have been added to the cache.
              // It's the perfect time to display a "New content is
              // available; please refresh." message in your web app.
              console.log('New content is available; please refresh.');
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
              console.log('Content is cached for offline use.');
            }    
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:',     error);
    });
}
Run Code Online (Sandbox Code Playgroud)

第一个控制台日志(显示“新内容可用;请刷新”)需要做什么来显示?

更具体地说,如何在 index.html 更改时触发此代码运行(如果脚本文件名更改)。

NOt*_*Dev 5

让我们一步一步地分解它。

  1. navigator.serviceWorker.register 当有效的 Service Worker 存在已经建立时,Promise 被解析
  2. registration.onupdatefound 注册一个事件监听器,当 Service Worker 的 HTTP 请求被解析为其他文件时(或第一次找到 SW 时)
  3. registration.installing.onstatechange 为新的 Service Worker 的生命周期变化注册一个监听器(从安装到安装,从安装到激活等)
  4. if (installingWorker.state === 'installed')过滤掉除installed-之外的所有状态,因此在安装每个新软件后将执行其正分支
  5. if (navigator.serviceWorker.controller)检查页面当前是否由任何(以前的)Service Worker 控制。如果为 true,那么我们将在此处处理上述更新场景。

总结一下 - 这console.log将在正确安装更新的(不是第一个)Service Worker 后执行。

index.html更改后不会触发。仅检查 Service Worker 代码(由serviceWorker.register方法指向)。另请注意,通常浏览器(或至少是 Chrome?)在下载当前版本后的 24 小时内不会检查新的软件版本。另请注意,如果 Service Worker 文件使用过于激进的缓存标头发送,则为 Service Worker 文件设置的普通旧 HTTP 缓存可能会在这里搞砸。