[PWA] 19. Cache the Avatars

Source: Internet
Author: User

The cache the avatars is little different from the 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 t Heir avatars frequently.

Self.addeventlistener (' Fetch ',function(event) {varRequesturl =NewURL (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) {returnResponse | |fetch (event.request); })  );});

functionServeavatar (Request) {//Avatar URLs look like:  //avatars/sam-2x.jpg  //But Storageurl had the-2x.jpg bit missing.  //Use this URL to store & match the image in the cache.  //This means is the store one copy of each avatar.  varStorageurl = 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!  returnCaches.open (Contentimgscache). Then (function(cache) {returnCache.match (Storageurl). Then (function(response) {varNetfetchresponse = Fetch (Request). Then (function(networkresponse) {cache.put (Storageurl, Networkresponse.clone ()); returnNetworkresponse;             }); returnResponse | |Netfetchresponse; })      })}

[PWA] 19. Cache the Avatars

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.