前置知识: HTML5

Service-Worker与PWA

00:00
1 min Advanced 2026/6/14

Service Worker与PWA

1. Service Worker 概述

Service Worker浏览器后台独立于网页脚本,充当网络代理,支持离线缓存推送通知和后台同步

生命周期:Installing → Installed(Waiting) → Activating → Activated → Redundant

if ('serviceWorker' in navigator) {
  navigator.serviceWorker
    .register('/sw.js', { scope: '/' })
    .then((reg) => console.log('注册成功'))
    .catch((err) => console.error('注册失败:', err));
}

2. 生命周期事件

const CACHE_NAME = 'app-v1';
const CACHE_URLS = ['/', '/index.html', '/styles.css', '/app.js'];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches
      .open(CACHE_NAME)
      .then((cache) => cache.addAll(CACHE_URLS))
      .then(() => self.skipWaiting())
  );
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches
      .keys()
      .then((names) =>
        Promise.all(names.filter((n) => n !== CACHE_NAME).map((n) => caches.delete(n)))
      )
      .then(() => self.clients.claim())
  );
});

3. 缓存策略

策略说明适用场景
Cache First优先缓存静态资源
Network First优先网络API 请求
Stale While Revalidate缓存即时响应,后台更新非关键 API
// Cache First
self.addEventListener('fetch', (event) => {
  event.respondWith(caches.match(event.request).then((cached) => cached || fetch(event.request)));
});

4. PWA 基础

{
  "name": "我的应用",
  "short_name": "我的App",
  "start_url": "/",
  "display": "standalone",
  "theme_color": "#1976d2",
  "icons": [{ "src": "/icons/192.png", "sizes": "192x192", "type": "image/png" }]
}

5. 推送通知与后台同步

// 推送通知
self.addEventListener('push', (event) => {
  const data = event.data?.json() ?? { title: '新消息' };
  event.waitUntil(self.registration.showNotification(data.title, { body: data.body }));
});

// 后台同步
self.addEventListener('sync', (event) => {
  if (event.tag === 'sync-data') event.waitUntil(syncData());
});

知识检测

学习进度

-- 已学文档
--% 知识覆盖率

学习推荐

专注模式