Jayy
Jayy

Reputation: 123

How to stop a PWA from caching my website

I have a simple PWA, that I update and change from Github pages.

When I make an update to the website, It doesn't show on the devices using the website, because (at least I think) its being cached. I don't have any service workers to cache the site.

Even a normal refresh from the website (using all of these)

Doesn't refresh it and shows the changes. On iOS I manually have to go into settings and clear the website data to see the changes.

How can i fix this?

Upvotes: 11

Views: 16319

Answers (2)

Shano
Shano

Reputation: 361

Use Network First (Network Falling Back to Cache)

https://developers.google.com/web/tools/workbox/modules/workbox-strategies#network_first_network_falling_back_to_cache

For requests that are updating frequently, the network first strategy is the ideal solution. By default, it will try to fetch the latest response from the network. If the request is successful, it’ll put the response in the cache. If the network fails to return a response, the cached response will be used.

Upvotes: 5

Francesco
Francesco

Reputation: 10830

When you make a page reload, a new check is done to verify if a new SW version is available. However you need then to close all your app browser tabs in order to install the new service worker version.

In Chrome Dev Tools you can check the "Update on Reload" checkbox on the Application tab. This is useful for development.

I would suggest to read the Google docs about it.

Plus, if you want to learn more details about PWAs have a look at my articles.


UPDATE

The browser checks for updates automatically after navigations (at latest every 24h). However you can also trigger the update manually (for example you can have a timer and trigger it once per hour or according to your needs):

navigator.serviceWorker.register('/sw.js').then(reg => {
  // ...

  // Trigger this after your timeout
  reg.update();
});

Alternatively you can use the updatefound event in order to detect in your code that a new sw version in available:

The onupdatefound property of the ServiceWorkerRegistration interface is an EventListener property called whenever an event of type statechange is fired; it is fired any time the ServiceWorkerRegistration.installing property acquires a new service worker.

navigator.serviceWorker.register('/sw.js').then(reg => {
  reg.addEventListener('updatefound', () => {

    const newSW = reg.installing;
    newSW.addEventListener('statechange', () => {

      // Check service worker state
      if (newSW.state === 'installed') {
          // A new SW is available and installed.
          // You can update the page directly or better
          // show a notification to the user to prompt for a page reload 
          // and inform about the new version available
         }
       });
      });
    });

Upvotes: 2

Related Questions