[PWA] Caching with Progressive libraries
Mainly introduce two libaraies: sw-precache and sw-toolbox.
Install:
npm install --save-dev sw-precache
Types of caching
Broadly, there are two types of caching
Precaching—We'll precache items that the app will always need immediately and will update with the application version. This is the primary job of sw-precache.
Runtime caching—This is how we cache everything else. The sw-toolbox library provides five ways to do this: network first, cache first, fastest, cache only, and network only. If you've ever read Jake Archibald's The Offline Cookbook you'll be familiar with these.
The Offline Cookbook describes five types of caching, all supported by sw-toolbox. The types with asterisks are used in Redder.
- Network first *—We can assume the reader of our app wants the most recent Reddit posts. For post titles we're always going to check the network first. This is also the strategy we're going to build in this codelab.
- Cache first *—Your first thought about about Reddit articles is that we would also want to load this from the network first. But the service worker has code to background load articles when the app launches and when a new subreddit is selected. Since the articles tend not to change after they've been created, we've chosen to look for them in the cache first.
- Fastest—Though not implemented, we could also have used this strategy for article caching. In this strategy, simultaneous requests are made to both the cache and the network. The application gets whichever returns first.
- Cache Only *—Because they don't change often, subreddits will be retrieved on the application's first page load and served from the cache thereafter. A more mature application would periodically refresh the list to pick up new subreddit names. In either case, an update to the service worker will also update the subreddit names.
- Network Only—This strategy is also not implemented in Redder. The network-only strategy is the same as not caching at all. Since it's possible that something you don't want cached would get picked up by one of the other strategies, this gives you a way to explicitly exclude paths from caching.
Gulpfile:
'use strict'; var gulp = require('gulp');
var path = require('path');
var swPrecache = require('sw-precache'); gulp.task('make-service-worker', function(callback) {
var rootDir = 'app'; swPrecache.write(path.join(rootDir, 'serviceworker.js'), {
staticFileGlobs: [rootDir + '/**/*.{html,css,png,jpg,gif}',
rootDir + '/js/*.js'],
stripPrefix: rootDir
});
});
It tells the rootDir is 'app', and use write() method to create a file called serivceworker.js and cache all the static files.
Runtime caching
Runtime caching is configured by adding an array of caching strategy objects to the options object. At a minimum, each caching strategy object requires a urlPattern
and a handler
, though some caching strategies require more. Generally, the whole property looks something like this:
runtimeCaching: [
{
urlPattern: /some regex/,
handler: 'cachingStrategy'
},
{
urlPattern: /some regex/,
handler: 'cachingStrategy'
}
// Repeat as needed.
],
The urlPattern
property is a regular expression used to match file requests to a caching strategy. The handler
property is the name of a caching strategy for the specified regular expression.
For Redder, let's see how to do running caching for post title.
Since title change frequently, so we need 'networkFirst'.
'use strict'; var gulp = require('gulp');
var path = require('path');
var swPrecache = require('sw-precache'); gulp.task('make-service-worker', function(callback) {
var rootDir = 'app'; swPrecache.write(path.join(rootDir, 'serviceworker.js'), {
staticFileGlobs: [rootDir + '/**/*.{html,css,png,jpg,gif}',
rootDir + '/js/*.js'],
stripPrefix: rootDir,
runtimeCaching: [
{
urlPattern: /https:\/\/www\.reddit\.com\/r\/\w{1,255}\.json/, //http://www.reddit.com/r/subredit_name.json
handler: 'networkFirst'
}
]
});
});
Using the right cache
we're caching subreddits, titles, and articles and we're using three different caching strategies to do it. We're going to give our caches names to identify them. To the subreddits caching pattern add an options
property, with a cache
property named 'titles'
.
runtimeCaching: [
{
urlPattern: /https:\/\/www\.reddit\.com\/r\/\w{1,255}\.json/,
handler: 'networkFirst',
options: {
cache: {
name: 'titles'
}
}
}],
Background sync the runtime caches
Redder has a bonus trick. It uses background synchronization to prefill the runtime caches. It does this for subreddits, titles, and articles. Exactly how it works and when it's triggered isn't important to this codelab. What is important is that it uses caches with particular names and they need to match what's in gulpfile.js
. As with runtime caching, background syncing doesn't work with links to non-reddit articles.
Copy the sync.js
file from caching-with-libraries/
to work/app/
. Add the importScripts
property to the write()
function. Make it import a service worker file called sync.js
, located in your app/
directory.
importScripts: ['sync.js']
'use strict'; var gulp = require('gulp');
var path = require('path');
var swPrecache = require('sw-precache'); gulp.task('make-service-worker', function(callback) {
var rootDir = 'app'; swPrecache.write(path.join(rootDir, 'serviceworker.js'), {
staticFileGlobs: [rootDir + '/**/*.{html,css,png,jpg,gif}',
rootDir + '/js/*.js'],
stripPrefix: rootDir,
runtimeCaching: [
{
urlPattern: /https:\/\/www\.reddit\.com\/r\/\w{1,255}\.json/, //http://www.reddit.com/r/subredit_name.json
handler: 'networkFirst'
}
],
importScripts: ['sync.js'] // in app folder
});
});
Turn on debugging
The sw-toolbox library has a debugging option. Turning this on will make sw-precache print status messages to the DevTools console.
importScripts: ['config.js','sync.js']
config.js:
toolbox.options.debug = true;
Open the dev tool:
Simulating offline and low latency conditions
Visit some categroies and turn off the network. Visit the one you alread clicked:
You will see it fallback to cache.
Add a navigation fallback
But if you visit the one which you haven't visit, it will report error.
The point of progressive web apps is so that our website works off line and in poor network conditions. A good progressive web app uses precaching and background syncing and other such capabilities to provide something to the user regardless of network conditions.
We're not omnipotent. Eventually, the user's going to request a resource that can't be retrieved from either the network or the caches. For that we want to create a fallback page to show when a requested resource isn't available.
Add the following to the options object
in the swPrecache.write()
method.
navigateFallback: 'message.html'
[PWA] Caching with Progressive libraries的更多相关文章
- PWA(Progressive Web App)入门系列:(一)PWA简单介绍
前言 PWA做为一门Google推出的WEB端的新技术,长处不言而喻.但眼下对于相关方面的知识不是非常丰富.这里我推出一下这方面的新手教程系列.提供PWA方面学习. 什么是PWA PWA全称Progr ...
- Progressive Web Apps入门
PC和Mobile开发技术演进 PC方向,从客户端到富客户端,到现在广泛使用的Web. 移动方向,目前主要还是原生应用和Mobile Web,PWA相关技术是未来发展方向. PWA的概念 ...
- 缓存&PWA实践
缓存&PWA 实践 一.背景 从上一篇<前端动画实现与原理分析>,我们从 Performance 进行动画的性能分析,并根据 Performance 分析来优化动画.但,前端不仅仅 ...
- ****微信小程序架构解析
| 导语 微信小程序的公测掀起了学习小程序开发的浪潮,天生跨平台,即用即走.媲美原生体验.完善的文档.高效的开发框架,小程序给开发者带来了很多惊喜.通过这篇文章和大家一起分析小程序的架构,分享开发 ...
- 一起脱去小程序的外套和内衣 - 微信小程序架构解析
版权声明:本文由渠宏伟 原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/760767001484042227 来源:腾云阁 ...
- [io PWA] Great libraries and tools for great Progressive Web Apps
sw-toolbox: Github It provides a cononical implementation of all the runtime caching strategies that ...
- [PWA] Keynote: Progressive Web Apps across all frameworks
PWA: Add to home screen Angular Universal Server side rendering: for achieving better proference on ...
- 说说 PWA 和微信小程序--Progressive Web App
作者:云图图链接:https://zhuanlan.zhihu.com/p/22578965来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 利益相关:微信小用户,谷歌小 ...
- 关于PWA ( Progressive web apps )
渐进式Web应用程序使用现代Web API以及传统的渐进式增强策略来创建跨平台Web应用程序.这些应用程序无处不在,并提供多种功能,使其具有与本机应用程序相同的用户体验优势.这套文档告诉您需要了解的所 ...
随机推荐
- marquee标签制作轮播图
http://qy-0824.blog.163.com/blog/static/725075422011214142226/ 缺点是仅能控制轮播的速度.鼠标悬停暂停等,并不能给其指定链接.触摸滑动.分 ...
- Ajax请求ashx一般处理程序实现文件下载
具体功能为,在文件数据列表中选择一行,点击表格上方的下载按钮,下载文件.由于表格中不包含文件路径,只能取到在数据库表中的ID,所以具体实现就是这样:首先点击一行,获取点击的一行数据的ID,用Ajax传 ...
- QNetworkRequest 请求类
QNetworkRequest Class Header: #include <QNetworkRequest>qmake: QT += networkSince: ...
- 学习Swift -- 协议(上)
协议(上) 协议是Swift非常重要的部分,协议规定了用来实现某一特定工作或者功能所必需的方法和属性.类,结构体或枚举类型都可以遵循协议,并提供具体实现来完成协议定义的方法和功能.任意能够满足协议要求 ...
- 学习Swift--方法
方法 方法是与某些特定类型相关联的函数.类.结构体.枚举都可以定义实例方法:实例方法为给定类型的实例封装了具体的任务与功能.类.结构体.枚举也可以定义类型方法:类型方法与类型本身相关联.类型方法与 O ...
- 转:靠谱的代码和DRY
http://www.cppblog.com/vczh/archive/2014/07/15/207658.html 靠谱的代码和DRY 上次有人来要求我写一篇文章谈谈什么代码才是好代码,是谁我已经忘 ...
- “未能加载文件或程序集file:///E:/MoneySet.dll或它的某一个依赖项,试图加载格式不正确的程序,行203,位置5. 文件:MReportSet.resx”,
http://bbs.csdn.net/topics/390334265 1.右键卸载项目2.右键选择编辑工程文件,在打开的文件的最后一行</project>之前加以下内容: <Pr ...
- HDU 3507 Print Article 斜率优化
Print Article Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)To ...
- Contest20140710 sequence
sequence|sequence.in|sequence.out 题目描述: 给定一个整数K和长为N的数列{Ai},求有多少个子串(不含空串)的和为K的倍数.(在这里子串表示{A[i]..A[j]} ...
- BZOJ 1003 物流运输trans
Description 物流公司要把一批货物从码头A运到码头B.由于货物量比较大,需要n天才能运完.货物运输过程中一般要转停好几个码头.物流公司通常会设计一条固定的运输路线,以便对整个运输过程实施严格 ...