博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[PWA] 17. Cache the photo
阅读量:4677 次
发布时间:2019-06-09

本文共 3597 字,大约阅读时间需要 11 分钟。

To cache photo, You need to spreate cache db to save the photo. So in wittr example, we cache the text already, if there in the wittr there is photo, we will 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 only cache assets, static imgs, css and js.

var staticCacheName = 'wittr-static-v7';var contentImgsCache = 'wittr-content-imgs';var allCaches = [  staticCacheName,  contentImgsCache];self.addEventListener('install', function(event) {  event.waitUntil(    caches.open(staticCacheName).then(function(cache) {      return cache.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 at the beginning we define the  cache name for photo .

 

self.addEventListener('activate', function(event) {  event.waitUntil(    caches.keys().then(function(cacheNames) {      return Promise.all(        cacheNames.filter(function(cacheName) {          return cacheName.startsWith('wittr-') &&                 !allCaches.includes(cacheName);        }).map(function(cacheName) {          return caches.delete(cacheName);        })      );    })  );});

'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 each 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) {  var requestUrl = new URL(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 assets  event.respondWith(    caches.match(event.request).then(function(response) {      return response || fetch(event.request);    })  );});

 

The servePhoto(): 

we want to make sure two things:

  • we don't care the photo size, 800px,200px or 40px
  • because respond object can be only access once, so we need clone() the original one and use clone one for the cahce, return the original one to the browser.
function servePhoto(request) {  var storageUrl = request.url.replace(/-\d+px\.jpg$/, '');  return caches.open(contentImgsCache).then(function(cache) {    return cache.match(storageUrl).then(function(response) {      if (response) return response;      return fetch(request).then(function(networkResponse) {        cache.put(storageUrl, networkResponse.clone());        return networkResponse;      });    });  });}

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) {        cache.put(storageUrl, networkResponse.clone());        return networkResponse;      });

 

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

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

你可能感兴趣的文章
sql三大范式
查看>>
关于TP5模板输出时间戳问题--A non well formed numeric value encountered
查看>>
js延迟加载
查看>>
如何在win 2008 server和win 7上add web site
查看>>
[Selenium]如何实现上传本地文件
查看>>
★不评价别人的生活,是一个人最基本的修养
查看>>
MySQL里执行SHOW INDEX结果中Cardinality的含义
查看>>
centos 7 下vnc弹出窗口太小解决方法
查看>>
SpringCloud Feign的分析
查看>>
64位Ubuntu 编译 hadoop源码
查看>>
使用MD5WithRSA来签名和验签(.NET)
查看>>
QQ登录JS SDK教程,调用openapi接口
查看>>
Socket编程
查看>>
为什么需要输入验证码?
查看>>
【spring 4】AOP:动态代理
查看>>
十六进制转化二进制[c]
查看>>
Create Index using NEST .NET
查看>>
异常:This application has no explicit mapping for /error, so you are seeing this as a fallback.
查看>>
垮平台开发平台
查看>>
使用wordpress自带ajax方法
查看>>