1
votes

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

1 Answers

5
votes

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