Progressive web app

From findscripter/everything-skills · View interactive version

Progressive web app is an AI agent skill from the GitHub repository findscripter/everything-skills. 当需要让 Web 应用可离线、可安装、像原生应用时使用;产出 manifest.json、Service Worker(含 install/activate/fetch 与缓存策略)、offline.html 与安装提示逻辑;不适用于纯静态站点、需要后台原生能力或仅做常规性能优化。触发词:PWA、Service Worker、离线、添加到主屏幕、Workbox、可安装

How to use this skill

Skill file

何时使用

满足以下任一场景时使用本技能:

不该用边界:

三大支柱:HTTPS(生产环境注册 SW 的前提,localhost 开发例外)、Web 应用清单 manifest.json(决定可安装性与主屏外观)、Service Worker sw.js(拦截请求、管理缓存、提供离线能力)。

步骤

交付清单(最少必须包含):

步骤 1:Web 应用清单 manifest.json

定义安装后的外观,须在 <head> 中用 <link rel="manifest"> 链接。

{
  "name": "My Awesome PWA",
  "short_name": "MyPWA",
  "description": "A fast, offline-capable Progressive Web App.",
  "start_url": "/",
  "scope": "/",
  "display": "standalone",
  "orientation": "portrait-primary",
  "background_color": "#ffffff",
  "theme_color": "#0055ff",
  "icons": [
    { "src": "/assets/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" },
    { "src": "/assets/icons/icon-512x512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
  ]
}

关键字段:display 取 standalone(隐藏浏览器 UI)/ minimal-ui / browser;图标 purpose: "maskable" 启用 Android 自适应图标(内容保持在中心 80% 安全区);screenshots 可选,但桌面端 Chrome 增强安装弹窗需要它。

步骤 2:HTML 外壳 index.html

除 <link rel="manifest"> 与 <meta name="theme-color"> 外,iOS Safari 不完全使用清单,需补充 apple 系列 meta:

<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#0055ff">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<meta name="apple-mobile-web-app-title" content="MyPWA">
<link rel="apple-touch-icon" href="/assets/icons/icon-192x192.png">

页面可放一个默认隐藏的安装按钮 <button id="install-btn" hidden>Install App</button>,并在底部 <script src="/app.js"></script>。

步骤 3:注册 SW 与安装提示 app.js

// Service Worker 注册
if ('serviceWorker' in navigator) {
  window.addEventListener('load', async () => {
    try {
      const reg = await navigator.serviceWorker.register('/sw.js');
      console.log('[App] SW registered, scope:', reg.scope);
    } catch (err) { console.error('[App] SW registration failed:', err); }
  });
}

// 安装提示(添加到主屏幕)
let deferredPrompt;
const installBtn = document.getElementById('install-btn');
window.addEventListener('beforeinstallprompt', (e) => {
  e.preventDefault();            // 阻止移动端自动迷你信息栏
  deferredPrompt = e;
  if (installBtn) installBtn.hidden = false;
});
if (installBtn) {
  installBtn.addEventListener('click', async () => {
    if (!deferredPrompt) return;
    deferredPrompt.prompt();
    const { outcome } = await deferredPrompt.userChoice;
    console.log('[App] Install outcome:', outcome);
    deferredPrompt = null;
    installBtn.hidden = true;
  });
}
window.addEventListener('appinstalled', () => console.log('[App] PWA installed'));

步骤 4:Service Worker sw.js

缓存版本(关键:每次部署必须递增)

const CACHE_VERSION = 'v1';
const STATIC_CACHE = `static-${CACHE_VERSION}`;
const DYNAMIC_CACHE = `dynamic-${CACHE_VERSION}`;
const APP_SHELL = ['/', '/index.html', '/styles.css', '/app.js',
  '/assets/icons/icon-192x192.png', '/offline.html'];

install — 预缓存 App Shell,结尾 self.skipWaiting() 立即激活:

self.addEventListener('install', (event) => {
  event.waitUntil(caches.open(STATIC_CACHE).then((c) => c.addAll(APP_SHELL)));
  self.skipWaiting();
});

activate — 清理旧缓存,结尾 self.clients.claim() 立即接管所有页面:

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

fetch — 按资源类型选缓存策略(仅处理本源 GET):

self.addEventListener('fetch', (event) => {
  const { request } = event;
  const url = new URL(request.url);
  if (request.method !== 'GET' || url.origin !== location.origin) return;

  // A 缓存优先:静态资源(快、容忍陈旧)
  if (url.pathname.match(/\.(css|js|png|jpg|svg|woff2)$/)) {
    event.respondWith(cacheFirst(request)); return;
  }
  // B 网络优先:HTML 页面(求新,失败回退缓存)
  if (request.headers.get('Accept')?.includes('text/html')) {
    event.respondWith(networkFirst(request)); return;
  }
  // C 陈旧时重验证:API 数据(先快后新)
  if (url.pathname.startsWith('/api/')) {
    event.respondWith(staleWhileRevalidate(request)); return;
  }
});

async function cacheFirst(request) {
  const cached = await caches.match(request);
  if (cached) return cached;
  try {
    const res = await fetch(request);
    (await caches.open(STATIC_CACHE)).put(request, res.clone());
    return res;
  } catch { return new Response('Asset unavailable offline', { status: 503 }); }
}
async function networkFirst(request) {
  try {
    const res = await fetch(request);
    (await caches.open(DYNAMIC_CACHE)).put(request, res.clone());
    return res;
  } catch { return (await caches.match(request)) || caches.match('/offline.html'); }
}
async function staleWhileRevalidate(request) {
  const cache = await caches.open(DYNAMIC_CACHE);
  const cached = await cache.match(request);
  const fetchPromise = fetch(request).then((res) => { cache.put(request, res.clone()); return res; });
  return cached || fetchPromise;
}

指令

示例

生产捷径:用 Workbox 替代手写策略(CDN 仅为演示,生产用 npm + 打包器):

importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
const { registerRoute } = workbox.routing;
const { CacheFirst, NetworkFirst, StaleWhileRevalidate } = workbox.strategies;
const { precacheAndRoute } = workbox.precaching;

precacheAndRoute(self.__WB_MANIFEST || []); // 由构建插件注入
registerRoute(({ request }) => request.destination === 'image', new CacheFirst());
registerRoute(({ request }) => request.mode === 'navigate', new NetworkFirst());
registerRoute(({ request }) => request.destination === 'script', new StaleWhileRevalidate());

上线前自检清单:

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.