我如何从 Workbox 实际显示更新的 index.html?

How do I actually display my updated index.html from Workbox?

我有一个完全静态的站点 - index.html 和一些 CSS/JS/PNG 文件。我想使用服务工作者来缓存所有这些。似乎 Workbox 应该使这变得容易。这是我的 sw.js:

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.5.0/workbox-sw.js');
workbox.precaching.precacheAndRoute([]);
workbox.routing.registerNavigationRoute('/index.html');

这是我的构建脚本:

const workboxBuild = require("workbox-build");

// NOTE: This should be run *AFTER* all your assets are built
const buildSW = async () => {
  console.log("Generating sw.js...")

  const {count, size, warnings} = await workboxBuild.injectManifest({
    swSrc: "src/sw.js",
    swDest: "build/sw.js",
    globDirectory: "build",
    globPatterns: [
      "**/*.{js,css,html,png}",
    ]
  })

  warnings.forEach(console.warn);
  console.log(`${count} files will be precached, totaling ${size} bytes.`);
}

buildSW();

这似乎一切正常。构建脚本运行,service worker 被激活,我的网站即使在我离线时也能继续工作。太棒了!

然后我对index.html做一些修改。我重新加载我的页面。我在控制台中看到这条消息,表明它已经缓存了我的 index.html,尽管它仍然在浏览器中显示旧的:

Precaching 1 file. 35 files are already cached.

我相信这是正确的,它在显示缓存后缓存新的 index.html。那么下次重新加载它应该显示新的 index.html,对吗?

错了!重新加载,还是显示原来的index.html。如此重复多次,没有变化。要真正看到新的 index.html,正常的重新加载将永远不起作用,我需要执行 ctrl+shift+R。

这不可能是它应该的工作方式,对吧?我一定遗漏了一些明显的东西,但我的代码非常简单,实际上是从 Workbox 网站上的示例中提取的,我看不出我哪里搞砸了。

编辑:我输入 a ridiculously simple example of this problem on GitHub。我觉得很愚蠢-这个例子很简单,但我仍然不明白为什么它会这样。

好吧,我在创建赏金后不久就愚蠢地找到了答案。正如 https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle 所说:

"Once successfully installed, the updated worker will wait until the existing worker is controlling zero clients. (Note that clients overlap during a refresh.)"

因此刷新永远不会切换到新版本,您必须完全关闭应用程序中所有打开的选项卡,然后再次导航到它。这似乎确实有效。