Hexo 配置 ServiceWorker 实现 PWA

hexo-service-worker 是一个可以让 Hexo 拥有 PWA 支持的插件,能够默认的把站点中 public 内的所有静态资源包括 htmlcssjsimage 等文件缓存起来,达到离线可访问的效果,实现 PWA。

实现前提

网站必须是https

PWA 是什么

PWA,即 Progressive Web App, 是提升 Web App 的体验的一种新方法,能给用户原生应用的体验。

PWA 不是某一项技术,或者某一个新的产物;而是一系列 Web 技术与标准的集合与应用。通过应用这些新的技术与标准,可以从安全、性能和体验三个方面,优化我们的 Web App。所以,其实 PWA 本质上依然是一个 Web App。

包含的技术:

  • Web App Manifest
  • Service Worker
  • Cache API 缓存
  • Push、Notification 推送与通知
  • Background Sync 后台同步

安装插件

1
2
3
npm i hexo-service-worker -d
# 或者
yarn add hexo-service-worker -d

配置 _config.yml 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# PWA -- offline config passed to sw-precache.
service_worker:
maximumFileSizeToCacheInBytes: 52428800
staticFileGlobs:
- public/**/*.{js,txt,html,xml,json,css,png,jpg,gif,svg,eot,ttf,woff,woff2,ico,cur}
- public/manifest.json
stripPrefix: public
verbose: true
runtimeCaching:
- urlPattern: /*
handler: cacheFirst
options:
origin: tiven.cn
- urlPattern: /*
handler: cacheFirst
options:
origin: cdn.bootcdn.net

在 hexo 生成静态文件时,hexo-service-worker会根据配置,进行缓存配置。

  • staticFileGlobs 可以使用正则来匹配某个目录,缓存 public 文件夹下面的指定静态资源。
  • runtimeCaching 是配置某个域名下使用到的静态资源,支持配置多个 origin 域。

生成配置 manifest.json 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{
"name": "xxxx",
"short_name": "xx",
"description": "description...",
"theme_color": "#222",
"background_color": "#eee",
"display": "standalone",
"orientation": "portrait-primary",
"Scope": "/",
"start_url": "/",
"icons": [
{
"src": "/images/logo/logo-96.png",
"sizes": "96x96",
"type": "image/png",
"purpose": "any"
},
{
"src": "/images/logo/logo-128.png",
"sizes": "128x128",
"type": "image/png",
"purpose": "any"
},
{
"src": "/images/logo/logo-144.png",
"sizes": "144x144",
"type": "image/png",
"purpose": "any"
},
{
"src": "/images/logo/logo-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "/images/logo/logo-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
}
],
"splash_pages": null
}

所有 iconssrc 路径,sizes 尺寸大小、type 类型都需要一一对应。

  • display 控制了应用的显示模式,它有四个值可以选择:fullscreenstandaloneminimal-uibrowser

    1. fullscreen 全屏显示, 所有可用的显示区域都被使用, 并且不显示状态栏
    2. standalone 独立应用模式,这种模式下打开的应用有自己的启动图标,并且不会有浏览器的地址栏。因此看起来更像一个 Native App
    3. minimal-ui 该应用程序将看起来像一个独立的应用程序,与 standalone 相比,该模式会多出地址栏。 样式因浏览器而异。
    4. browser 默认的设置,一般来说,会和正常使用浏览器打开样式一致。
  • orientation 控制 Web App 的方向。设置某些值会具有类似锁屏的效果(禁止旋转)。具体的值包括:any, natural, landscape, landscape-primary, landscape-secondary, portrait, portrait-primary, portrait-secondary

引用 manifest.json

在公共 _data/head.ejs 中添加下代码

1
<link rel="manifest" href="/manifest.json">

部署后可以打开,控制台 / Application / Manifest / Service Workers / Storage,进行调试、查看缓存情况。

参考文档

  • https://www.npmjs.com/package/hexo-service-worker