[PWA] 19. Cache the avatars

本文介绍了一种使用Service Worker缓存头像和照片的方法。针对频繁更换头像的用户,该方案通过缓存已有数据并同时从网络获取最新头像来确保内容更新。对于照片,则直接从缓存中读取。

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

 

转载于:https://www.cnblogs.com/Answer1215/p/5522116.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值