N
N
newaitix2021-04-04 20:30:28
JavaScript
newaitix, 2021-04-04 20:30:28

How to update the cache?

Service worker code.

var version='5.3.7.1';
self.addEventListener('install',function(ev){
  ev.waitUntil(caches.open(version).then(function(cache){
    if(location.protocol=='http:'||location.protocol=='https:'){
      return fetch('/resource.json').then(function(res){
        return res.json();
      }).then(function(files){
        return cache.addAll(files);
      });
    }
  }));
  self.skipWaiting();
});
self.addEventListener('activate',function(ev){
  ev.waitUntil(caches.keys().then(function(keyList){
    return Promise.all(keyList.map(function(key){
      if(version!=key){
        return caches.delete(key);
      }
    }));
  }));
});
self.addEventListener('fetch',function(ev){
  ev.respondWith(caches.match(ev.request).then(function(res){
    return res||fetch(ev.request).then(function(res){
      var resToCache=res.clone();
      caches.open(version).then(function(cache){
        if(ev.request.method!='POST'){
          cache.put(ev.request,resToCache);
        }
      });
      return res;
    }).catch(function(){
      return caches.match('/offline.html');
    });
  }));
});

After the new version of sw appears, I refresh the page, the new sw cache takes effect, but the resources do not change, because the browser cache (memory cache) is used when loading resources.
6069f77d20311651956279.png
Thus, the service worker is updated, but the data remains the same.
Only if you check the disable cache checkbox in the console, the data will be loaded again, and fresh data will get into the service worker cache.
6069f7564b9e8600258471.png
How to deal with it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2021-04-05
@newaitix

Is there a assembler? In any, you can configure so that a hash is added to the file name.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question