简体   繁体   中英

How and When should we write to cache in Service Workers?

  • Cache all requests from an app without explicitly specifying urlsToCache . So I will cache stuff under fetch event.
  • To respond to requests from the cache.
  • Update the cache when fetch is success.

Initially,

this.addEventListener('fetch', function(event) {
    var fetchReq = event.request.clone(),
        cacheReq = event.request.clone();
    event.respondWith(fetch(fetchReq).then(function(response) {
        var resp = response.clone();
        caches.open(CACHE_NAME).then(function(cache) {
            req = event.request.clone();
            cache.put(req, resp);
        });
        return response;
    }).catch(function() {
        return caches.match(cacheReq);
    }));
});

The offline situations were handled perfectly well. But the problem here was with the slow connections. The user has to wait till fetch times out or throws an error to get the response from cache.

self.addEventListener('fetch', function(event) {
    var cacheRequest = event.request.clone();
    event.respondWith(caches.match(cacheRequest).then(function(response) {
        if(response) return response;
        var fetchRequest = event.request.clone();
        return fetch(fetchRequest).then(function(response) {
            var responseToCache = response.clone();
            caches.open(cache_name).then(function(cache) {
                var cacheSaveRequest = event.request.clone();
                cache.put(cacheSaveRequest, responseToCache);
            });
            return response;
        });
    }));
});

With the cache taking precedence, the responses served were fine. But the problem here is that when the code updates. When /public/main.css served via sw is updated, on page reload only the cache is served, the updated content is not served.

I also tried modifying the cache_name to cache-v2 from cache-v1 (so that sw binary diff exists and sw is updated and that old cache can be cleared), and cleared cache-v1 on activate event. But it gave rise to new problems where two service workers were running at the same time under the same Registration ID . More on this is in this other SO question: How to stop older service workers?

Two service workers running at the same time are not technically a problem—it's working as designed. (See my answer to How to stop older service workers? ) Make sure that you close other tabs that might have an older version of your service worker active.

You're running into the inevitable tradeoffs between the different cache vs. network scenarios here. If you haven't yet read through the offline cookbook , it's a great starting point when trying to decide which caching strategy works best for your specific resources.

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