'Is there a way to implement "update service worker on reload"?

I understand that when you reload a tab, the waiting service worker won't be activated, because the previous tab and new tab are overlapped.

But I am wondering if there is a way to implement it by delaying the closing of the old tab or opening of the new tab, such that we can skip waiting and activate the waiting service worker?

I tried this:

    const wb = new Workbox("service-worker.js");
    wb.addEventListener("waiting", () => {
      window.addEventListener('beforeunload', async () => {
        await wb.messageSkipWaiting();
      });
    });

And it does activate the waiting service worker on reload, but the reload sometimes hangs forever, because there is race condition that reloading needs to fetch index.html and assets from the service worker, while the activation of service worker might interrupt the request. For example, if the old SW was handling the request, and suddenly it is replaced by the new SW, the request could hang.

Not sure if there is a better to handle this.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source