Files
blog/content/posts/hugo-pwa/index.md
konjacpotato 91c25fbe00
All checks were successful
Gitea Actions Demo / build-and-deploy-to-local-server (push) Successful in 2m59s
Gitea Actions Demo / deploy-to-remote-server (push) Successful in 2s
post: hugo pwa
2025-06-17 21:09:30 +08:00

87 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
date: '2025-06-17T21:02:27+08:00'
draft: false
title: 'Hugo静态网站增加对PWA的支持'
---
Progressive Web App (PWA) 是一种增强型网页应用形式,具备:
- 可被安装(添加到主屏幕)
- 离线访问
- 类似原生 App 的体验
实现 PWA 核心需要以下三个要素:
1. manifest.json: 用于描述你的 Web App 的外观和行为,如图标、名称、主题色等。
2. service-worker.js: 是一个浏览器后台脚本,可以拦截网络请求、缓存资源,实现离线访问。
3. 在 HTML 中注册 Service Worker 和引入 manifest
**第一步:添加 manifest.json**
创建 static/manifest.json
```json
{
"name": "Hugo PWA",
"short_name": "PWA",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#317EFB",
"icons": [
{
"src": "/icons/icon-192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "/icons/icon-512.png",
"type": "image/png",
"sizes": "512x512"
}
]
}
```
**第二步:添加 service-worker.js**
在 static/service-worker.js 中添加:
```javascript
const cacheName = 'v1';
const cacheAssets = [
'/',
'/index.html',
'/style.css',
// 可以添加其他需要缓存的资源路径
];
self.addEventListener('install', e => {
e.waitUntil(
caches.open(cacheName).then(cache => {
console.log('Caching files...');
return cache.addAll(cacheAssets);
})
);
});
self.addEventListener('fetch', e => {
e.respondWith(
fetch(e.request).catch(() => caches.match(e.request))
);
});
```
**第三步:在页面中注册 service worker 和引入 manifest**
修改你的```layouts/partials/head.html```(或 ```baseof.html``` 中的 ```<head>``` 部分):
```html
<link rel="manifest" href="/manifest.json" />
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(reg => console.log('Service Worker registered', reg))
.catch(err => console.log('Service Worker failed', err));
}
</script>
```