简体   繁体   中英

How to make persistent PWA cache?

I've been trying to make offline only PWAs for Android, but the site's cache keeps clearing every so often. Is there any way to make the cache stay permanently?

You can define caching strategies for static assets and data requests for your service worker.

In the following article about service workers and caching strategies I list the different strategies and describe when it makes more sense to implement a specific one.

You can cache static assets and provide them offline when the SW is installing. Those files should be only the "minimum" version of your app (usually called app shell). Because of this, the cache.addAll method rejects the promise if it is not possible to get any of the resources. This means the service worker will install successfully only if all the targeted resources are cached.

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open('staticAssetsCache').then(function(cache) {
      return cache.addAll(
        [
          '/css/bootstrap.css',
          '/css/styles.css',
          '/js/jquery.min.js',
          '/offline.html'
        ]
      );
    })
  );
});

You can also cache HTTP GET Requests, for example below the stale while revalidate strategy that returns the data from the cache, if available, and in the background attempts to fetch and cache a newer version from the network:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.open('www.my-web-app.com')
      .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;
          })

        // response contains cached data, if available
        return response || fetchPromise;
      })
    })
  );
});

If you are using Angular or Workbox library, https://dev.to/paco_ita/create-progressive-web-apps-with-angular-workbox-pwa-builder-step-4-27d for more details.

I believe I read somewhere iOS Safari and Chrome would invalidate the cache frequently to get new updates. No logic behind it, just re-fetching the files.


Solution:

(In a recent Chrome devlog, it mentions a reduction in frequency from 3 days to 1)

to prevent the clearing of the cache / IndexDB I found this .

if (navigator.storage && navigator.storage.persist)
  // '.persist()' will silently pass or trigger a dialog
  navigator.storage.persist().then(function(persistent) {
    alert(persistent ? 'persistent' : 'denied');
  })
else
  alert('not available - iOS / ancient Android?');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM