name: progressive-web-app description: 渐进式Web应用,包括服务工作者、Web清单、离线支持、安装提示。用于可安装的Web应用、离线功能、推送通知,或处理服务工作者注册、缓存策略、清单配置错误。 license: MIT
渐进式Web应用 (PWA)
构建像原生应用一样工作的Web应用,支持离线和可安装性。
Web应用清单
{
"name": "My Application",
"short_name": "MyApp",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#000000",
"icons": [
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }
]
}
服务工作者
const CACHE_NAME = 'app-v1';
const STATIC_ASSETS = ['/', '/index.html', '/styles.css', '/app.js'];
// 安装
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(STATIC_ASSETS))
);
});
// 使用缓存优先策略的获取
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(cached => {
if (cached) return cached;
return fetch(event.request).then(response => {
if (response.status === 200) {
const clone = response.clone();
caches.open(CACHE_NAME).then(cache => cache.put(event.request, clone));
}
return response;
});
})
);
});
安装提示
let deferredPrompt;
window.addEventListener('beforeinstallprompt', e => {
e.preventDefault();
deferredPrompt = e;
showInstallButton();
});
async function installApp() {
if (!deferredPrompt) return;
deferredPrompt.prompt();
const { outcome } = await deferredPrompt.userChoice;
console.log('安装结果:', outcome);
deferredPrompt = null;
}
推送通知
async function subscribeToPush() {
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: VAPID_PUBLIC_KEY
});
await sendSubscriptionToServer(subscription);
}
PWA检查清单
- [ ] HTTPS已启用
- [ ] Web清单已配置
- [ ] 服务工作者已注册
- [ ] 离线回退页面
- [ ] 响应式设计
- [ ] 快速加载(在3G上<3秒)
- [ ] 可安装