[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 handlerproperty 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‘
时间: 2024-10-06 01:19:30

[PWA] Caching with Progressive libraries的相关文章

PWA(Progressive Web App)入门系列:(一)PWA简介

前言 PWA做为一门Google推出的WEB端的新技术,好处不言而喻,但目前对于相关方面的知识不是很丰富,这里我推出一下这方面的入门教程系列,提供PWA方面学习. 什么是PWA PWA全称Progressive Web App,直译是渐进式WEB应用,是 Google 在 2015 年提出,2016年6月才推广的项目.是结合了一系列现代Web技术的组合,在网页应用中实现和原生应用相近的用户体验. 所谓的P(Progressive)这里有两层含义,一方面是渐进增强,让WEB APP的体验和功能能够

PWA(Progressive Web App)入门系列:(一)PWA简单介绍

前言 PWA做为一门Google推出的WEB端的新技术,长处不言而喻.但眼下对于相关方面的知识不是非常丰富.这里我推出一下这方面的新手教程系列.提供PWA方面学习. 什么是PWA PWA全称Progressive Web App,直译是渐进式WEB应用,是 Google 在 2015 年提出,2016年6月才推广的项目.是结合了一系列现代Web技术的组合.在网页应用中实现和原生应用相近的用户体验. 所谓的P(Progressive)这里有两层含义,一方面是渐进增强,让WEB APP的体验和功能能

Progressive Web Apps入门

PC和Mobile开发技术演进 PC方向,从客户端到富客户端,到现在广泛使用的Web. 移动方向,目前主要还是原生应用和Mobile Web,PWA相关技术是未来发展方向. PWA的概念 Progressive Web App (中文翻译为:渐进式Web应用)带来的体验将网络应用的优点与原生应用的优点相结合.用户在浏览器中第一次访问时就能体会到它们的好处,因为不需要进行任何安装.在用户随着时间的推移增进与应用的关系后,其功能会变得越来越强大.它即使在不可靠网络上也能快速加载.能够发送相关推送通知

一起脱去小程序的外套和内衣 - 微信小程序架构解析

版权声明:本文由渠宏伟  原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/760767001484042227 来源:腾云阁 https://www.qcloud.com/community 作者介绍: 渠宏伟,腾讯高级工程师,从事Web前端开发5年,先后负责企鹅电竞.腾讯视频VIP.腾讯OA开发框架.腾讯微信HR助手等项目.对Web前端架构..NET架构有丰富的经验. 微信小程序的公测掀起了学习小程序开发的浪潮,天生跨

借助Service Worker和cacheStorage缓存及离线开发 (转载)

一.缓存和离线开发 说得HTML5离线开发,我们通常第一反应是使用html5 manifest缓存技术,此技术已经出现很多年了,我以前多次了解过,也见过一些实践案例,但是却从未在博客中介绍过,因为并不看好. 为什么不看好呢?用一句话解释就是“投入产出比有些低”. 对于web应用,掉线不能使用是理所当然的,绝不会有哪个开发人员会因为网页在没网的时候打不开被测试MM提bug,或者被用户投诉,所以,我们的web页面不支持离线完全不会有什么影响.但如果我们希望支持离线,会发现,我投入的精力和成本啊还真不

****微信小程序架构解析

| 导语   微信小程序的公测掀起了学习小程序开发的浪潮,天生跨平台,即用即走.媲美原生体验.完善的文档.高效的开发框架,小程序给开发者带来了很多惊喜.通过这篇文章和大家一起分析小程序的架构,分享开发经验. 一.小程序介绍 1.小程序特点 2.小程序演示 视频地址: https://v.qq.com/x/page/w0353d7co6y.html 3.小程序为什么那么快 Page Frame Native预先额外加载一个WebView当打开指定页面时,用默认数据直接渲染,请求数据回来时局部更新返

【文章学习】监控网页卡顿、崩溃

[学习文章] 1.如何监控网页的卡顿:https://zhuanlan.zhihu.com/p/39292837 2.如何监控网页的崩溃:https://zhuanlan.zhihu.com/p/40273861 知识延展.补充: 1.PWA (Google Progressive Web App)概念 渐进式网页应用.一个利用现代浏览器的能力来达到类似APP的用户体验的技术,由Google实现,让浏览器打开的网址像APP一样运行在手机上.让Web App和Native App之间的差距更小.

[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 you need for you dynamice content. sw-precache: Github It takes care of caching and maintaing all the resources in your app shell sw-helpers: Github

[PWA] Keynote: Progressive Web Apps across all frameworks

PWA: Add to home screen Angular Universal Server side rendering: for achieving better proference on init loading Angular 2 CLI ng new myapp --mobile sw-precache: with webpack: sw-toolbox: run time caching angular2 material design: *shellRender and *s