[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.
相关文章
- Maven报错:The packaging for this project did not assign a file to the build artifact[通俗易懂]
- The method assertEquals(double, double) from the type Assert is deprecated
- 【错误记录】Flutter 编译报错 ( The parameter ‘‘ can‘t have a value of ‘null‘ because of its type, but the im )
- ORA-01326: compatability of 9.0 or greater required to build into the logstream ORACLE 报错 故障修复 远程处理
- ORA-26748: The one-to-one transformation function string encountered the following error: string ORACLE 报错 故障修复 远程处理
- ORA-26800: Apply not the only subscriber for “string”.”string”. ORACLE 报错 故障修复 远程处理
- ORA-29848: error occurred in the execution of ODCIINDEXMERGEPARTITION routine ORACLE 报错 故障修复 远程处理
- ORA-31435: an error occurred during the purge operation ORACLE 报错 故障修复 远程处理
- ORA-48108: invalid value given for the diagnostic_dest init.ora parameter ORACLE 报错 故障修复 远程处理
- ORA-55566: SQL statement issued when the database was not open for queries ORACLE 报错 故障修复 远程处理
- ORA-55568: The maximum query length (mql) value should be atmost string based on the current _highthreshold_undoretention setting. ORACLE 报错 故障修复 远程处理
- ORA-55600: The table “string”.”string” is already enabled for Flashback Archive ORACLE 报错 故障修复 远程处理
- ORA-06514: PL/SQL: The remote call cannot be handled by the server ORACLE 报错 故障修复 远程处理
- ORA-13034: Invalid data in the SDO_ORDINATE_ARRAY in SDO_GEOMETRY object ORACLE 报错 故障修复 远程处理
- ORA-13906: The tablespace is not of the right type. ORACLE 报错 故障修复 远程处理
- Springboot 启动报错 Disconnected from the target VM, address: ‘127.0.0.1:5406’, transport: ‘socket’详解程序员
- what is the difference of select single and select up to one row in abap详解编程语言
- 类型MySQL: Unlocking the Power of Binary Data Types(mysql二进制数据)
- Exploring the Dynamic Duo: The Power of Solr MongoDB Integration(solrmongodb)
- Maximizing Database Efficiency: The Power of Oracle CBO Optimization(oraclecbo优化)
- Exploring the Power of Linux Jiffies: Uncovering the Secrets Behind Efficient CPU Time Management.(linuxjiffes)
- Exploring the Power of as86 Linux: The Ultimate Guide for Beginners!(as86linux)
- Exploring the World of Video Editing with Linux: A Comprehensive Guide(视频linux)
- Exploring the Power of Linux with Hydra: A Comprehensive Guide to Network Security(linuxhydra)