17

What I am trying to achieve:

  • render page with loader/spinner

  • if service-worker.js is registered and active, then check for updates

    • if no updates, then remove loader
    • if updatefound and new version installed, then reload the page
  • else register service-worker.js
    • when updatefound, meaning new one was installed, remove loader

I am using sw-precache module for me to generate service-worker.js and following registration code:

window.addEventListener('load', function() {

  // show loader
  addLoader();

  navigator.serviceWorker.register('service-worker.js')
    .then(function(swRegistration) {

      // react to changes in `service-worker.js`
      swRegistration.onupdatefound = function() {
        var installingWorker = swRegistration.installing;
        installingWorker.onstatechange = function() {
          if(installingWorker.state === 'installed' && navigator.serviceWorker.controller){

            // updated content installed
            window.location.reload();
          } else if (installingWorker.state === 'installed'){

            // new sw registered and content cached
            removeLoader();
          }
        };
      }

      if(swRegistration.active){
        // here I know that `service-worker.js` was already installed
        // but not sure it there are changes
        // If there are no changes it is the last thing I can check
        // AFAIK no events are fired afterwards
      }

    })
    .catch(function(e) {
      console.error('Error during service worker registration:', e);
    });
});

After reading the spec it is clear that there are no handlers for something like updatenotfound. Looks like serviceWorker.register checks if service-worker.js changed internally by running get-newest-worker-algorithm, but I cannot see similar methods exposed via public api.

I think my options are:

  • wait for couple of seconds after service worker registration becomes active to see if onupdatefound is fired
  • fire custom events from service-worker.js code if cache was not updated

Any other suggestions?


Edit:

I've came up with some code which solves this issue by using postMessage() between SW registration and SW client (as @pate suggested)

Following demo tries to achieve checks through postMessage between SW client and SW registration, but fails as SW code is already cached DEMO


Edit:

So by now it looks like I cannot implement what I want because:

  1. when service worker is active you cannot check for updates by evaluating some code in SW - this is still the same cached SW, no changes there
  2. you need to wait for onupdatefound, there is nothing else that will notify of changes in SW
  3. activation of older SW comes before onupdatefound
  4. if there is no change, nothing fires after activation
  5. SW registration update() is immature, keeps changing, Starting with Chrome 46, update() returns a promise that resolves with 'undefined' if the operation completed successfully or there was no update
  6. setting timeout to postpone view rendering is suboptimal as there is no clear answer to how long should it be set to, it depends on SW size as well
Ivar
  • 4,350
  • 2
  • 27
  • 29
  • 1
    Hi, do you have any update on this ? – Samuel Maisonneuve Jun 21 '18 at 11:03
  • Actually I do not, apps in production do this crazy refresh after initial load has happened (view rendered) and changes were detected subsequently – Ivar Jun 21 '18 at 12:58
  • Ok thanks for your answer – Samuel Maisonneuve Jun 22 '18 at 13:50
  • unbelievable, tried an entire day .. have the exact same usecase.did you end up implementing a timer? I'm thinking about it, most apps have some loader screens for a couple seconds anyways. Could also be disabled by using session storage I guess. Still seems unreliable to me – maxischl May 07 '23 at 18:49
  • @maxischl this was "some time" ago. I'm not entirely sure if the API is still the same or if it changed for the better. – Ivar May 08 '23 at 13:56

2 Answers2

4

The other answer, provided by Fabio, doesn't work. The Service Worker script has no access to the DOM. It's not possible to remove anything from the DOM or, for instance, manipulate any data that is handling DOM elements from inside the Service Worker. That script runs separately with no shared state.

What you can do, though, is send messages between the actual page-running JS and the Service Worker. I'm not sure if this is the best possible way to do what the OP is asking but can be used to achieve it.

  1. Register an onmessage handler on the page
  2. Send a message from the SW's activate or install event to the page
  3. Act accordingly when the message is received on the page

I have myself kept SW version number in a variable inside the SW. My SW has then posted that version number to the page and the page has stored it into the localStorage of the browser. The next time the page is loaded SW posts it current version number to the page and the onmessage handler compares it to the currently stored version number. If they are not the same, then the SW has been updated to some version number that was included in the mssage. After that I've updated the localStorage copy of the version number and done this and that.

This flow could also be done in the other way around: send a message from the page to the SW and let SW answer something back, then act accordingly.

I hope I was able to explain my thoughts clearly :)

pate
  • 4,937
  • 1
  • 19
  • 25
  • Great suggestion, I've done a plunker with a hacked solution [plunker demo](https://embed.plnkr.co/s9ozu0ntcQuD5touoWIr/). Will wait for more responses for now. – Ivar Aug 21 '17 at 14:00
  • Yes, I was not claiming to supply the full procedure, but just the concept. When I wrote ***removeLoader();*** in the SW script, I meant that something has to be done there (a message? an event checking?). – Fabio Marzocca Aug 21 '17 at 15:03
  • One caveat is that its OK if SW is not registered yet (first installation), but if it is then events are going to be fired from SW which is active already and it will say that nothing changed. So it seems that you cannot guarantee that `onupdatefound` will not be triggered after you receive those. – Ivar Aug 28 '17 at 15:20
0

The only way that pops up in my mind is to start the loader normally and then remove it in the service-worker, in the install function. I will give this a try, in your service-worker.js:

self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    }).then(function() {
        ***removeLoader();***
        return self.skipWaiting();
    })
  );
});
Fabio Marzocca
  • 1,573
  • 16
  • 36
  • It looked like it should solve an issue but this event is fired only if worker changes. https://w3c.github.io/ServiceWorker/#service-worker-global-scope-install-event – Ivar Aug 21 '17 at 14:05