[PWA] 17. Cache the photo

Source: Internet
Author: User

To cache photo, you need to spreate cache db to save the photo. wittr example, we cache the text already, if there in the wittr there is photo, we'll create cache for it, so next Time we can fetch from cache.

For the incoming photo, we also need-to-create cache for them.

For the ' Install ' event, we have only cache assets, static IMGs, CSS and JS.

varStaticcachename = ' Wittr-static-v7 ';var contentimgscache = ' Wittr-content-imgs ';varAllcaches =[Staticcachename, contentimgscache];self.addeventlistener (' Install ',function(event) {Event.waituntil (Caches.open (staticcachename). Then (function(cache) {returnCache.addall (['/skeleton ',        ' Js/main.js ',        ' Css/main.css ',        ' Imgs/icon.png ',        ' Https://fonts.gstatic.com/s/roboto/v15/2UX7WLTfW3W8TclTUvlFyQ.woff ',        ' Https://fonts.gstatic.com/s/roboto/v15/d-6IYplOFocCacKzxwXSOD8E0i7KZn-EPnyo3HZu7kw.woff '      ]); })  );});

Here we don ' t cache dynamic photos. But on the beginning we define the cache name for photo.

Self.addeventlistener (' Activate ',function(event) {Event.waituntil (Caches.keys (). Then (function(cachenames) {returnPromise.all (Cachenames.filter (function(cachename) {return cachename.startswith (' wittr-') &&! allcaches.includes (cachename); }). Map (function(cachename) {returnCaches.Delete(CacheName);    })      ); })  );});

The ' Activate ' event is the place to clean the old version Cahce but keep the current version cache and photo cache.

In ' Fetch ' event, this is the place we want to cache the photos.

For the request, we want to check,

    • Whether we have the cache for the photo request?
    • If not, fetch from network and cache it.
Self.addeventlistener (' Fetch ',function(event) {varRequesturl =NewURL (Event.request.url); //Make sure the same Origin  if(Requesturl.origin = = =location.origin) {//serve cache with the skeleton    if(Requesturl.pathname = = = '/')) {Event.respondwith (Caches.match ('/skeleton ')); return; }    //Cache the photo    if(RequestUrl.pathname.startsWith ('/photos/') { event.respondwith (Servephoto (event.request)); return; }  }  //Cache the AssetsEvent.respondwith (Caches.match (event.request). Then (function(response) {returnResponse | |fetch (event.request); })  );});

The Servephoto ():

We want to make sure-things:

    • We don ' t care the photo size, 800px,200px or 40px
    • Because respond object can be is only access once, so we need Clone () the original one and use clone one for the CAHCE, retur n the original one to the browser.
functionServephoto (Request) {varStorageurl = Request.url.replace (/-\d+px\.jpg$/, "); returnCaches.open (Contentimgscache). Then (function(cache) {returnCache.match (Storageurl). Then (function(response) {if(response)returnresponse; returnFetch (Request). Then (function(networkresponse) {cache.put (Storageurl, Networkresponse.clone ()); returnNetworkresponse;    });  }); });}

So first, remove those px info: (/photos/awefaef-af23-fwq23f-800px.jpg)--(/photos/awefaef-af23-fwq23f)

var storageurl = Request.url.replace (/-\d+px\.jpg$/, ");

Second, clone the network response and return origial one to browser and clone one to cache

return Fetch (request). Then (function(networkresponse) {        networkresponse.clone () );         return networkresponse;      });

Unitl now, we is able to cache the photo, event in the offline mode, we is still able to see the photos return from the Cache.

[PWA] 17. Cache the photo

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.