为hexo博客启用PWA能力
准备
博客已启用https支持
安装hexo-offline并增加配置
1 | npm install hexo-offline --save |
然后在站点_config.yml中配置如下内容:
# Offline
## Config passed to sw-precache
## https://github.com/JLHwung/hexo-offline
offline:
maximumFileSizeToCacheInBytes: 10485760
staticFileGlobs:
- public/**/*.{js,html,css,png,jpg,gif,svg,json,xml,eot,ttf,woff,woff2}
stripPrefix: public
verbose: true
runtimeCaching:
# CDNs - should be cacheFirst, since they should be used specific versions so should not change
- urlPattern: /*
handler: cacheFirst
options:
origin: cdn.bootcss.com
个人配置,仅供参考。
取得manifest.json文件
PWA 需要有一个 manifest.json
文件,你需要创建这个文件并将其放置到根目录的 source 目录下。推荐一款工具快速生成 manifest 文件:App Manifest Generator,直接生成无烦恼。
内容示例:
{
"name": "青菜萝卜丁",
"short_name": "青菜萝卜丁",
"theme_color": "#2196f3",
"background_color": "#2196f3",
"display": "standalone",
"Scope": "/",
"start_url": "/",
"icons": [
{
"src": "/images/favicon-192x192.png",
"sizes": "192x192",
"type": "image/png",
"density": 4.0
}
],
"splash_pages": null
}
引用manifest.json文件
manifest.json
文件需要在 head 标签里引用,我使用的是 cactus 主题,所以我在 layout/_partials/head.ejs
文件中添加一句代码:
<link rel="manifest" href="/manifest.json">
增加其他内容
head.ejs文件
在head.ejs的head标签中增加
<meta name="theme-color" content="#1d1f21">
scripts.ejs文件
在scripts.ejs结尾处增加
<script type="text/javascript">
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register("/service-worker.js", {scope: '/'})
.then(registration => console.log('SW Registration Success!Scope: ', registration.scope))
.catch(err => console.log('SW Registration Failed! Error: ', err));
}
</script>
部署博客
部署你的博客!
检测
可以使用chrome扩展Lighthouse来出具一份你的博客对于PWA的相关检测报表,方式是:打开你的博客,直接运行它,稍等片刻,就会生成一份报告。