Search code examples
javascriptgoogle-chromecachingservice-workercacheapi

Service worker automatic update process


I have a doubt about the service worker update process. In my project there are 2 files related to sw:

"sw.js", placed in website root, will be NOT cached (by Cache API and Web Browser).

My service worker manages the cache of all statics files and all dynamic url pages.

Sometimes I need to update it and the client must detect that there's an update and do that immediatelly.

"sw_main.js" is the script that installs my sw. This file is cached by Cache API because my app must work offline.

Inside we can find:

var SW_VERSION = '1.2';
navigator.serviceWorker.register("sw.js?v=" + SW_VERSION, { scope: "/" }).then(....

The problem is: because sw_main.js is cached, if I change the SW_VERSION and then deploy online the webapp, all clients will not update because cannot see the changes in that file.

Which is the best way to manage the SW update process?

As I now, there are 3 ways to trigger sw update:

  1. push and sync events (but I'm not implementing these)
  2. calling .register() only if the service worker URL has changed (but in my case it's not possible because the sw_main.js is cached so I'm not able to change the SW url)
  3. navigation to an in-scope page (I think we've the same cache problem of point 2)

I read also this: "Your service worker is considered updated if it's byte-different to the one the browser already has".

That means that if I change the content of sw.js (that is not cached), the service worker will automatically detect the update?

Thank you


Solution

  • I found 2 possibile solutions.

    First of all I wanna say that it's better to cache (using pwa Cache API) also the sw.js because when you're offline, it will be requested by sw_main.js.

    FIRST SOLUTION:

    Use a the service worker's cache as a fallback and always attempt to go network-first via a fetch(). This only for sw.js and maybe sw_main.js. You lose some performance gains that a cache-first strategy offers, but the js file size is very light so I don't think it's a big problem.

    SECOND SOLUTION:

    If your cached sw.js file has changed? We can hook into "onupdatefound" function on the registered Service Worker. Even though you can cache tons of files, the Service Worker only checks the hash of your registered service-worker.js. If that file has only 1 little change in it, it will be treated as a new version. So this confirm my previous question! I'll try it!

    If it works, the second solution is the best