Service Worker get from cache then update cache

梦想与她 提交于 2019-12-11 04:45:49

问题


I'm using the following logic in my service worker (in my own words):

If cache exists, use it, but also update cache from the network for later

event.respondWith( // on `fetch`
    caches.open(CACHE)
        .then(function(cache) {
            return cache.match(request);
        })
        .then(function(matching) {
            if (matching) {
                requestAndUpdateCache(event);
                return matching;
            }
            ...

In addition to responding with the cached response, I also run this function called requestAndUpdateCache.

function requestAndUpdateCache(event){
    var url = event.request.url + '?t=' + new Date().getTime();
    fetch(url)
        .then(function(response){
            if (response && response.status === 200){
                caches.open(CACHE)
                    .then(function(cache){
                        cache.put(event.request, response.clone());
                    });
            }
        }, function(error){
            console.log(error);
        });
}

Questions: Does this function and its placement make sense to accomplish the logic outlined above?


回答1:


What you're describing is a stale-while-revalidate strategy.

The canonical place to look for implementations of different service worker caching strategies is Jake Archibald's The Offline Cookbook. There's a section that covers stale-while-revalidate, including the following code:

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;
      })
    })
  );
});


来源:https://stackoverflow.com/questions/41574723/service-worker-get-from-cache-then-update-cache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!