zoukankan      html  css  js  c++  java
  • [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;
             })
          })
    }
  • 相关阅读:
    SpringBoot校验(validation)
    序列化/反序列化
    全面的整理了原生js
    apache commons工具类简介
    刚从git上download的代码,有个工具类中某个类找不到
    Hadoop(三)手把手教你搭建Hadoop全分布式集群
    Hadoop(一)之初识大数据与Hadoop
    Hadoop(二)搭建伪分布式集群
    Git(一)之基本操作详解
    Git(二)Git几个区的关系与Git和GitHub的关联
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5522116.html
Copyright © 2011-2022 走看看