From 91c25fbe009e7a9d18e132803a23213087beb4bf Mon Sep 17 00:00:00 2001 From: konjacpotato Date: Tue, 17 Jun 2025 21:09:30 +0800 Subject: [PATCH] post: hugo pwa --- content/posts/hugo-pwa/index.md | 86 +++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 content/posts/hugo-pwa/index.md diff --git a/content/posts/hugo-pwa/index.md b/content/posts/hugo-pwa/index.md new file mode 100644 index 0000000..7671863 --- /dev/null +++ b/content/posts/hugo-pwa/index.md @@ -0,0 +1,86 @@ +--- +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``` 中的 `````` 部分): +```html + + +``` +