3

I have this one-page app with a dynamic URL built with a token, like example.com/XV252GTH and various assets, like css, favicon and such.

Here is how I register the Service Worker:

navigator.serviceWorker.register('sw.js');

And in said sw.js, I pre-cache the assets while installing:

var cacheName = 'v1';

var cacheAssets = [
    'index.html',
    'app.js',
    'style.css',
    'favicon.ico'
];

function precache() {
    return caches.open(cacheName).then(function (cache) {
        return cache.addAll(cacheAssets);
    });
}

self.addEventListener('install', function(event) {
    event.waitUntil(precache());
});

Note that the index.html (that registers the Service Worker) page is just a template, that gets populated on the server before being sent to the client ; so in this pre-caching phase, I'm only caching the template, not the page.

Now, in the fetch event, any requested resource that is not in the cache gets copied to it:

addEventListener('fetch', event => {
    event.respondWith(async function() {
        const cachedResponse = await caches.match(event.request);
        if (cachedResponse) return cachedResponse;       
        return fetch(event.request).then(updateCache(event.request));
    }());
});

Using this update function

function updateCache(request) {
    return caches.open(cacheName).then(cache => {
        return fetch(request).then(response => {
            const resClone = response.clone();
            if (response.status < 400)
                return cache.put(request, resClone);
            return response;
        });
    });
}

At this stage, all the assets are in the cache, but not the dynamically generated page. Only after a reload, can I see another entry in the cache: /XV252GTH. Now, the app is offline-ready ; But this reloading of the page kind of defeats the whole Service Worker purpose.

Question: How can I send the request (/XV252GTH) from the client (the page that registers the worker) to the SW? I guess I can set up a listener in sw.js

self.addEventListener('message', function(event){
    updateCache(event.request)
});

But how can I be sure that it will be honored in time, ie: sent by the client after the SW has finished installing? What is a good practice in this case?

yPhil
  • 8,049
  • 4
  • 57
  • 83

2 Answers2

5

OK, I got the answer from this page: To cache the very page that registers the worker at activation time, just list all the SW's clients, and get their URL (href attribute).

self.clients.matchAll({includeUncontrolled: true}).then(clients => {
    for (const client of clients) {
        updateCache(new URL(client.url).href);
    }
});
yPhil
  • 8,049
  • 4
  • 57
  • 83
  • 1
    I want to draw attention to my answer as I believe this is a cleaner solution and more commonly/best practiced. – Aaron3219 Apr 19 '19 at 20:06
3

Correct me if I understood you wrong!
You precache your files right here:

var cacheAssets = [
    'index.html',
    'app.js',
    'style.css',
    'favicon.ico'
];

function precache() {
    return caches.open(cacheName).then(function (cache) {
        return cache.addAll(cacheAssets);
    });
}

It should be clear that you cache the template since you cache it before the site gets build and this approach is not wrong, at least not for all types of files.
Your favicon.ico for example is a file that you would probably consider as static. Also, it does not change very often or not at all and it isn't dynamic like your index.html.
Schema Source

It should also be clear why you have the correct version after reloading the page since you have an update function.

The solution to this problem is the answer to your question:

How can I send the request (/XV252GTH) from the client (the page that registers the worker) to the SW?

Instead of caching it before the service-worker is installed you want to cache it if the back end built your web page. So here is how it works:

  1. You have an empty cache or at least a cache without your index.html.
  2. Normally a request would be sent to the server to get the index.html. Instead, we do a request to the cache and check if the index.html is in the cache, at least if you load the page for the first time.
  3. Since there is no match in the cache, do a request to the server to fetch it. This is the same request the page would do if it would load the page normally. So the server builds your index.html and sends it back to the page.
  4. After receiving the index.html load it to the page and store it in the cache.

An example method would be Stale-while-revalidate: enter image description here

If there's a cached version available, use it, but fetch an update for next time.

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.open('mysite-dynamic').then(function(cache) {
      return cache.match(event.request).then(function(response) {
        var fetchPromise = fetch(event.request).then(function(networkResponse) {
          cache.put(event.request, networkResponse.clone());
          return networkResponse;
        })
        return response || fetchPromise;
      })
    })
  );
});

Source

Those are the basics for your problem. Now you got a wide variety of options you can choose from that use the same method but have some additional features. Which one you choose is up to you and without knowing your project in detail no one can tell you which one to choose. You are also not limited to one option. In some cases you might combine two or more options together.

Google wrote a great guide about all the options you have and provided code examples for everything. They also explained your current version. Not every option will be interesting and relevant for you but I recommend you to read them all and read them thoroughly.

This is the way to go.

Aaron3219
  • 2,168
  • 4
  • 11
  • 28
  • Hi Aaron you seem to be quite an expert in PWA, I am hiving similar issues, I can setup can cache the shell but not able to update. can you take a quick look. https://stackoverflow.com/questions/55797611/tying-to-update-pwa-swupdate-isenabled-is-true-but-not-calling-the-subscribed-m – ishandutta2007 Apr 23 '19 at 07:48
  • Thanks for the compliment. Unfortunately I am not familiar with Angular. I have worked with other front end frameworks but not this one. – Aaron3219 Apr 23 '19 at 10:48
  • I don't think issue is there with angular integration, that part worked fine. what I am struggling in making it upgrade, the issue is with my understanding of `SwUpdate` . If you can just take a look at the constructor of `PwaService` and tell me if there are any issues , it would be enough. – ishandutta2007 Apr 23 '19 at 10:56
  • Well, at least I can't see any. That's probably the reason why you haven't received any answers so far. I don't know how familiar you are with PWAs. If you are relatively new you could have forgotten steps to update a service worker. Unregister your service worker, delete the cache (specifically from your page), enable "Update on reload"... Otherwise, it could be that you just have the old service worker running with an old cache. Service workers don't update their selves on default if you change the script of a service worker. – Aaron3219 Apr 23 '19 at 11:22
  • Thanks Aaron.Yes I am new to PWA, I dont know much about Unregister, delete the cache, Update on reload. I dont think I have done these. Let me read about these. My expectation was changing `ngsw-config.json` would trigger `this.swUpdate.available` but it is not triggering even though `this.swUpdate.isEnabled` is true. – ishandutta2007 Apr 23 '19 at 12:26
  • I did not test this, but it looks waaay cleaner than my hack, so I accepted it ; thank you! – yPhil Oct 07 '22 at 12:00