[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.

时间: 2024-10-16 08:37:10

[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 display on the page anymore, we want to clean it. And also every 5 mins we want to clean the photo data. export default function IndexController(container)

[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)

shiro的权限控制应用,集成spring项目,密码错误次数过多短时间锁定

以前对shiro都是一知半解,最近系统学了一遍shiro并集成到了在做的项目中. 下面就详细向大家描述一下shiro的用法. 首先是对spring的配置文件,如下: 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3

第三十四章 metrics(2)- 搭建metrics平台

一.基本架构图 1.整个架构组件: java客户端 dropwizard-metrics:springboot.hystrix的metric体层使用了这个,所以我们需要自己封装向statsd发包的方法,来发送这些metrics给statsd java-statsd-client:直接进行计数并且非常方便的向statsd发送这些metrics(向statsd发包的方法已经封装好了) statsd graphite carbon carbon-relay carbon-cache whisper g

Hibernate二级缓存

第一级缓存:事务范围的缓存.Session缓存.存放元数据和预定义SQL.只读缓存. 第二级缓存:进程范围或者集群范围.由SessionFactory负责管理.SessionFactory的外置缓存.SessionFactory这个级别维护的缓存.二级缓存是针对整个应用而不是某个特定的session. Session 如何判断持久化对象的状态的改变呢? Session 加载对象后会为对象值类型的属性复制一份快照.当Session 清理缓存时,比较当前对象和它的快照就可以知道那些属性发生了变化.

ehcache2.8.3入门示例:hello world

一.pom.xml 依赖项 1 <dependency> 2 <groupId>net.sf.ehcache</groupId> 3 <artifactId>ehcache</artifactId> 4 <version>2.8.3</version> 5 </dependency> 6 7 <dependency> 8 <groupId>org.slf4j</groupId>

DbContext 查询

使用LINQ to Entities来写查询语句 Entity Framework查询是使用的.NET Framework功能Language Integrated Query,AKA LINQ.LINQ与.NET的编程体验是紧密集成在一起的,它提供了强类型的查询,何谓强类型,各位自行补脑.与弱类型的查询相比,它提供了编译时检查来保证你的查询通过验证以及IntelliSense. LINQ是一个通用的查询框架,并不仅仅是针对Entity Framework或者数据库的,LINQ提供程序负责把LI

Java Integer 常量池

Integer类 Integer 类在对象中包装了一个基本类型 int 的值.Integer 类型的对象包含一个 int 类型的字段. 此外,该类提供了多个方法,能在 int 类型和 String 类型之间互相转换,还提供了处理 int 类型时非常有用的其他一些常量和方法. Integer i = 10 和 Integer j = new Integer(10) 的区别 1 1.publicstaticvoid main(String[] args){ 2 2.Integer i=10; 3 3

Sensor与android Manager机制

1.1 Sensor应用程序框架 这部分对于上层写应用的朋友来比较熟悉,我们通过一个简单的应用来分析框架层和底层的实现. 通常编写一个传感器的应用程序有以下步骤: l 通过调用 Context.getSystemService(SENSOR_SERVICE)获得传感器服务,实现返回的是封装了SensorService的SensorManager对象 l 调用SensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION)来获得指定类型的传感器对象,方