[PWA] 19. Cache the avatars

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[PWA] 19. Cache the avatars相关的知识,希望对你有一定的参考价值。

Cache the avatars is little different from cache photos. We need to serve the page with our cache data and also go to the network for fetch avatars in case some user like change their avatars frequently.

 

self.addEventListener(‘fetch‘, function(event) {
  var requestUrl = new URL(event.request.url);

  if (requestUrl.origin === location.origin) {
    if (requestUrl.pathname === ‘/‘) {
      event.respondWith(caches.match(‘/skeleton‘));
      return;
    }
    if (requestUrl.pathname.startsWith(‘/photos/‘)) {
      event.respondWith(servePhoto(event.request));
      return;
    }
    // TODO: respond to avatar urls by responding with
    // the return value of serveAvatar(event.request)
    if(requestUrl.pathname.startsWith(‘/avatars/‘)){
      event.respondWith(serveAvatar(event.request));
      return;
    }
  }

  event.respondWith(
    caches.match(event.request).then(function(response) {
      return response || fetch(event.request);
    })
  );
});

 

function serveAvatar(request) {
  // Avatar urls look like:
  // avatars/sam-2x.jpg
  // But storageUrl has the -2x.jpg bit missing.
  // Use this url to store & match the image in the cache.
  // This means you only store one copy of each avatar.
  var storageUrl = request.url.replace(/-\dx\.jpg$/, ‘‘);

  // TODO: return images from the "wittr-content-imgs" cache
  // if they‘re in there. But afterwards, go to the network
  // to update the entry in the cache.
  //
  // Note that this is slightly different to servePhoto!
  return caches.open(contentImgsCache)
      .then(function(cache){
         return cache.match(storageUrl).then(function(response){

             var netFetchResponse = fetch(request).then(function(networkResponse){
                 cache.put(storageUrl ,networkResponse.clone());
                 return networkResponse;
             });

             return response || netFetchResponse;
         })
      })
}

 

以上是关于[PWA] 19. Cache the avatars的主要内容,如果未能解决你的问题,请参考以下文章

[PWA] 18. Clean the photo cache

[PWA] 15. Using The IDB Cache And Display Entries

[PWA] 7. First Cache when installed

[PWA] 11. Serve skeleton cache for root

[PWA] Cache Third Party Resources from a CDN in a React PWA

[PWA] 8. Delete old cache and only keep one