Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 362
dumbmatter Avatar asked Sep 14 '18 03:09

dumbmatter


1 Answers

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.

like image 178
dumbmatter Avatar answered Nov 15 '22 14:11

dumbmatter