2

Is there any way to have service workers fetch the cached version, then attempt to do a network fetch, and if it's different than the cached version, put that new thing in the cache and replace the old asset in the DOM with the new one instantly (without having to refresh the page)?

Matias
  • 459
  • 1
  • 4
  • 14

1 Answers1

1

Hey yeah this is a very tricky situation but what I did was save a version number to my .env file on production release.

I then built this NPM package which will surface the Version number of the .env at build time. I could then use this number in my VueJS - PWA to check against the old currently cached version number, and then do a network request if they dont match.

https://www.npmjs.com/package/vue-enverywhere

Sweet Chilly Philly
  • 3,014
  • 2
  • 27
  • 37
  • I currently do a similar thing: I have a `version` variable in my service worker that's updated each time my app is. As a result, a new service worker is registered each time my app is (I use `skipWaiting` and `clients.claim`), clearing the old cache and building a new one, but it doesn't activate until the user refreshes the app. As a result, the user sees a stale version of the website until the next refresh. Any way to see the new version right away? – Matias May 01 '22 at 21:54
  • 1
    You need to now run a check in your vueApp `on load` if the version number of the PWA matches the clients version then do nothing, otherwise force the refresh. This will mean they always see the newest version – Sweet Chilly Philly May 01 '22 at 22:52
  • OK, that does indeed work. I could even add a banner on the bottom prompting the user to reload. However, is there any way to replace the assets with the new version without a reload? Kind of like HMR while in development? – Matias May 02 '22 at 03:09
  • 1
    Yup that's what i did as well, i put a banner up and they can request more data if they wish. To your Q i believe not, because of reactivity reasons. However, this problem is less relevant the longer your app is live because there are fewer changes. Well thats the case in my situation. Anyway my friend im happy that has helped, please upvote and mark ;) – Sweet Chilly Philly May 02 '22 at 03:44
  • 1
    Side note. If you really want to try do it with out a page load, you can use custom `:keys` on vue components which you manually update to trigger reactivity, but its a nightmare to code so GL: https://stackoverflow.com/questions/32106155/can-you-force-vue-js-to-reload-re-render – Sweet Chilly Philly May 02 '22 at 03:46
  • 1
    Hmm... OK, if it is indeed impossible, then a banner seems like the least invasive solution. Thanks for the help! :) – Matias May 02 '22 at 04:48