前端 PWA 开发指南:离线缓存与推送通知实现
常见误区
前端 PWA?这不仅仅是技术组合,而是一种现代化的 Web 应用模式。
- "PWA 有什么用,用户直接用浏览器不就好了"——结果用户体验差,无法离线访问
- "我有原生 App,不需要 PWA"——结果开发成本高,维护困难
- "PWA 就是加个 manifest 和 service worker,多简单"——结果功能不完整,用户体验差
事实上,PWA 不是简单的技术堆砌,而是构建完整的 Web 应用体验。
核心价值
- 离线访问:即使没有网络也能访问应用
- 安装到主屏幕:像原生 App 一样方便使用
- 推送通知:及时向用户发送重要信息
- 性能提升:缓存静态资源,加快加载速度
- 跨平台:一次开发,多平台运行
错误示例
<!-- 反面教材:不完整的 PWA 配置 -->
<!DOCTYPE html>
<html>
<head>
<title>我的 PWA 应用</title>
<!-- 缺少 manifest.json -->
<!-- 缺少 service worker -->
</head>
<body>
<h1>我的 PWA 应用</h1>
<p>这是一个 PWA 应用</p>
</body>
</html>
// 反面教材:简单的 service worker
self.addEventListener('install', event => {
console.log('Service Worker 安装');
});
self.addEventListener('activate', event => {
console.log('Service Worker 激活');
});
self.addEventListener('fetch', event => {
console.log('Service Worker 拦截请求');
});
正确实现
<!-- 正确的做法:完整的 PWA 配置 -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>我的 PWA 应用</title>
<!-- 添加 manifest.json -->
<link rel="manifest" href="/manifest.json">
<!-- 添加主题颜色 -->
<meta name="theme-color" content="#317EFB">
<!-- 添加 Apple Touch Icon -->
<link rel="apple-touch-icon" href="/icons/icon-192x192.png">
<!-- 添加预加载 -->
<link rel="preload" href="/style.css" as="style">
<link rel="preload" href="/script.js" as="script">
<link rel="stylesheet" href="/style.css">
</head>
<body>
<h1>我的 PWA 应用</h1>
<p>这是一个完整的 PWA 应用</p>
<button>发送通知</button>
<script src="/script.js"></script>
<script>
// 注册 service worker
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('Service Worker 注册成功:', registration.scope);
})
.catch(error => {
console.log('Service Worker 注册失败:', error);
});
});
}
</script>
</body>
</html>
// 正确的做法:manifest.json
{
"name": "我的 PWA 应用",
"short_name": "PWA 应用",
"description": "一个完整的 PWA 应用示例",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#317EFB",
"icons": [
{
"src": "/icons/icon-72x72.png",
"sizes": "72x72",
"type": "image/png",
"purpose": "any"
},
{
"src": "/icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
}
]
}
// 正确的做法:完整的 service worker
const CACHE_NAME = 'pwa-app-cache-v1';
const ASSETS_TO_CACHE = [
'/','/index.html','/style.css','/script.js','/manifest.json'
];
// 安装 Service Worker
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
return cache.addAll(ASSETS_TO_CACHE);
})
.then(() => self.skipWaiting())
);
});
// 激活 Service Worker
self.addEventListener('activate', event => {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
)
.then(() => self.clients.claim())
);
});
});
// 拦截网络请求
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
return response;
}
return fetch(event.request)
.then(response => {
if (response && response.status === 200 && response.type === 'basic') {
const responseToCache = response.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, responseToCache);
});
}
return response;
})
.catch(error => {
if (event.request.mode === 'navigate') {
return caches.match('/offline.html');
}
});
})
);
});
// 处理推送通知
self.addEventListener('push', event => {
const data = event.data.json();
const options = {
body: data.body,
icon: '/icons/icon-192x192.png',
badge: '/icons/icon-72x72.png',
data: { url: data.url }
};
event.waitUntil(
self.registration.showNotification(data.title, options)
);
});
// 处理通知点击
self.addEventListener('notificationclick', event => {
event.notification.close();
event.waitUntil(clients.openWindow(event.notification.data.url));
});
// 正确的做法:使用推送通知
function requestNotificationPermission() {
if ('Notification' in window) {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
console.log('通知权限已授予');
} else {
console.log('通知权限被拒绝');
}
});
}
}
function sendNotification() {
if ('serviceWorker' in navigator && 'PushManager' in window) {
navigator.serviceWorker.ready.then(registration => {
registration.showNotification('测试通知', {
body: '这是一条测试通知',
icon: '/icons/icon-192x192.png',
badge: '/icons/icon-72x72.png',
data: { url: '/' }
});
});
}
}
window.addEventListener('load', () => {
requestNotificationPermission();
const notificationBtn = document.getElementById('notification-btn');
if (notificationBtn) {
notificationBtn.addEventListener('click', sendNotification);
}
});
function checkPwaMode() {
const isPwa = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone || document.referrer.includes('android-app://');
if (isPwa) {
console.log('应用以 PWA 模式运行');
} else {
console.log('应用以浏览器模式运行');
}
}
checkPwaMode();
核心要点
综上所述,PWA 不是简单地添加 manifest 和 service worker,而是构建一个完整的 PWA 应用,包括离线访问、推送通知、安装到主屏幕等功能。
记住,PWA 不是替代原生 App,而是一种补充。它可以让你的 Web 应用获得类似原生 App 的体验,同时保持 Web 的跨平台优势。
所以,PWA 是现代 Web 开发的重要方向。
总结
- manifest.json:配置应用名称、图标、显示模式等
- Service Worker:实现离线缓存、推送通知等功能
- 离线访问:缓存静态资源,确保无网络时也能访问
- 安装到主屏幕:提供类似原生 App 的入口
- 推送通知:及时向用户发送重要信息
- 性能优化:缓存策略、预加载等
- 可访问性:确保 PWA 对所有用户都友好
- 跨平台:一次开发,多平台运行
