[PWA] 17. Cache the photo
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.
[PWA] 17. Cache the photo的更多相关文章
- [PWA] 18. Clean the photo cache
We cannot let photo always keep caching new data without clean the old data. If message is not displ ...
- [PWA] 19. Cache the avatars
Cache the avatars is little different from cache photos. We need to serve the page with our cache da ...
- 【Guava】Guava Cache用法
背景 缓存的主要作用是暂时在内存中保存业务系统的数据处理结果,并且等待下次访问使用.在日长开发有很多场合,有一些数据量不是很大,不会经常改动,并且访问非常频繁.但是由于受限于硬盘IO的性能或者远程网络 ...
- Highcharts指南
摘要 Highcharts图表控件是目前使用最为广泛的图表控件.本文将从零开始逐步为你介绍Highcharts图表控件.通过本文,你将学会如何配置Highcharts以及动态生成Highchart图表 ...
- Flash 二进制传图片到后台Java服务器接收
需求:把客户端处理过的图片返还给服务器Flash端代码 01 package {02 import com.adobe.images.JPGEncoder; 03 import ...
- 数据交互 ajax 初始化省
1 //初始化省 2 function initProvince() { 3 if( areaLvel == 0 ) { 4 return; 5 } 6 // 清空option 7 $("# ...
- 转:Highcharts图表控件的使用
摘要 Highcharts图表控件是目前使用最为广泛的图表控件.本文将从零开始逐步为你介绍Highcharts图表控件.通过本文,你将学会如何配置Highcharts以及动态生成Highchart图表 ...
- linux包之dmidecode
http://www.dmtf.org/standards/smbios Dmidecode 这款软件允许你在 Linux 系统下获取有关硬件方面的信息.Dmidecode 遵循 SMBIOS/DMI ...
- JBoss 系列二十一:JBossCache核心API
内容简介 本处介绍JBossCache相关的主要API,我们目的通过本部分描述,读者可以使用JBossCache API,在自己的应用中使用JBossCache. Cache接口 Cache 接口是和 ...
随机推荐
- spring mvc easyui tree 异步加载树
使用spring mvc 注解 异步加载一棵树 jsp: <ul id="orgInfoTree"></ul> $(function(){ loadOrgT ...
- prototype/constructor/__proto__之prototype简单应用
一.简单使用构造原型加prototype造简单的轮子. 1.想jQ那样获取HTML元素,先看JS代码 function Cmf() { //创建构造函数 this.arry = [] } Cmf.pr ...
- __call方法简介
作用:当程序试图调用不存在或不可见的成员方法时,PHP会先调用__call方法来储方法名及参数. __call方法包含两个参数:即方法名和方法参数.其中,方法参数是以数组形式存在的.
- ASP.NET Web API下Controller激活
一.HttpController激活流程 对于组成ASP.NET Web API核心框架的消息处理管道来说,处于末端的HttpMessageHandler是一个HttpRoutingDispatche ...
- 【Java】java的内存浅析
一.闲谈下 201407月记着那时候身体垮了下来,呵呵.想说,对自己的说,也是对大家的负责吧.那时候胸疼胸闷,然后几乎累垮了,我还坚持了一星期,那一星期真的迷迷糊糊.完全不能看代码,看代码就晕.一直想 ...
- c#,if 分支语句,条件运算符
//输入整数a和b, //若a²+b²大于100,则输出a²+b²百位以上数字, //否则输出两数之和 /*Console.Write("请输入整数a:"); int a = in ...
- Eclipse控制台中文乱码
换了OS真是,主要就是对Eclipse的配置操作不熟悉.用着不顺手.源文件一直都是按照google java style的做法保存为UTF-8.现在显示乱码,就得改Eclipse解码的配置为 UTF- ...
- network: Android 网络判断(wifi、3G与其他)
package mark.zeng; import Java.util.List; import Android.content.Context; import android.location.Lo ...
- Hadoop环境搭建-入门伪分布式配置(Mac OS,0.21.0,Eclipse 3.6)
http://www.linuxidc.com/Linux/2012-10/71900p2.htm http://andy-ghg.iteye.com/blog/1165453 为Mac的MyEcli ...
- centos 6.5 安装weixin
下载cpanm wget http://xrl.us/cpanm --no-check-certificate -O /sbin/cpanm && chmod +x /sbin/cpa ...