渐进式Web应用 progressive-web-app

渐进式Web应用(PWA)是一种现代Web开发技术,通过服务工作者实现离线缓存、Web清单支持应用安装、推送通知等功能。适用于构建可安装、高性能的Web应用,提升用户体验,增强Web应用的原生感。关键词:渐进式Web应用, PWA, 服务工作者, 离线支持, 可安装性, 推送通知, Web清单, 缓存策略。

前端开发 0 次安装 0 次浏览 更新于 3/7/2026

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秒)
  • [ ] 可安装