简体   繁体   中英

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

I have a completely static site - index.html and some CSS/JS/PNG files. I'd like to use a service worker to cache all of them. It seems that Workbox should make this easy. Here's my sw.js:

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

And here's my build script:

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

That all seems to work fine. The build script runs, the service worker is activated, and my site continues to work even when I'm offline. Fantastic!

Then I make some modifications to index.html. I reload my page. I see this message in the console, indicating that it has cached my index.html, although it's still showing the old one in the browser:

Precaching 1 file. 35 files are already cached.

I believe this is correct, it's caching the new index.html after displaying the cached one. So then next reload it should display the new index.html, right?

Wrong! Reload again, and the old index.html is still displayed. Repeat this many times, no change. To actually see the new index.html, a normal reload will never work, I need to do ctrl+shift+R.

This can't be how it's supposed to work, right? I must be missing something obvious, but my code is so simple and practically pulled from the examples on the Workbox website, I don't see where I am messing up.

EDIT: I put a ridiculously simple example of this problem on GitHub . I feel very stupid - the example is so simple, yet I still can't figure out why it behaves like it does.

Okay I stupidly figured out the answer shortly after creating a bounty. As https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle says:

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

So refreshing will never switch to the new version, you have to totally close all open tabs of your app and then navigate to it again. That does seem to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM