PWA 基础
Turn websites 到 installable Progressive Web Apps 使用 service 工作者 and manifests.
你将学到
- 什么 Progressive Web App (PWA) 是 and 它的 three pillars
- 如何 web app manifest 启用 installation and app-如 behavior
- 如何 service 工作者启用 offline 缓存 and background sync
- 当 PWA 是正确 choice 对比. native app
概念讲解
PWA Basics
A Progressive Web App (PWA) is a web application that uses modern web APIs to deliver an app-like experience — installable on the home screen, working offline, sending push notifications, and running full-screen. PWAs are built with the same HTML, CSS, and JavaScript you already know, plus two key additions: a web app manifest and a service worker. They are "progressive" because they work in any browser, and enhance to app-like behavior where the browser supports it.
The Three Pillars
- Installable — the web app manifest lets the browser offer an "添加到 Home Screen" prompt. Once installed, the PWA launches in its own window, without the browser chrome, with a custom icon and splash screen.
- Offline-capable — a service worker caches resources and API responses, so the app works without a network connection. This is the biggest difference from a traditional web app.
- App-like — full-screen display, custom themes, push notifications, and background sync make the PWA feel like a native app, not a website in a tab.
The Web App Manifest
The manifest is a JSON file linked from your HTML. It describes how the app should appear when installed:
{
"name": "My App",
"short_name": "MyApp",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#2563eb",
"icons": [{ "src": "icon-192.png", "大小": "192x192" }]
}
The display: standalone setting makes it open without browser UI. The icons are used for the home screen and splash screen. Once a valid manifest and a registered service worker exist, the browser can prompt installation.
Service Workers
A service worker is a JavaScript file that runs in the background, separate from the page. It acts as a programmable network proxy — it intercepts every fetch request and can respond from a cache instead of the network. This is how offline support works:
- On install, the service worker pre-caches the app shell (HTML, CSS, JS).
- On fetch, it checks the cache first (fast, offline-capable), then falls back to the network.
- On network success, it updates the cache for next time.
This "缓存-首先, network-fallback" strategy means the app loads instantly from cache and works offline. Other strategies (network-first, stale-while-revalidate) suit different needs.
When to Use a PWA
PWAs shine for content apps (news, catalogs), tools (editors, calculators), and any app where cross-platform reach matters more than deep native APIs. They are not ideal for apps needing heavy device access (camera, Bluetooth, files) or high-performance graphics (games). The biggest advantage: one codebase runs everywhere, with no app store review process. The biggest limitation: browser support for advanced APIs varies, and iOS Safari has historically lagged behind Chrome on PWA features.
示例代码
// Register the service worker (in your main JS)
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker.register("/sw.js")
.then(reg => console.log("SW registered:", reg.scope))
.catch(err => console.error("SW failed:", err));
});
}
// The service worker itself (sw.js)
const CACHE = "my-app-v1";
const ASSETS = ["/", "/index.html", "/styles.css", "/app.js"];
// Install: pre-cache the app shell
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE).then(cache => cache.addAll(ASSETS))
);
});
// Fetch: cache-first, then network
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then(cached => {
return cached || fetch(event.request).then(response => {
// Cache new responses for next time
const clone = response.clone();
caches.open(CACHE).then(cache => cache.put(event.request, clone));
return response;
});
})
);
});
主要 script registers service 工作者之后 page 加载. service 工作者 pre-caches app shell on 安装, 然后 serves 请求从 缓存首先, falling 后面到 network. 新 network 响应是 cached for 下一个时间. 这个制作 app 加载 instantly and 工作 offline.
动手试一试
- JSON Formatter
web app manifest 是 JSON — 格式 and 验证它 之前 deploying.
- JSON Validator
验证你的 manifest.JSON 语法 — malformed manifest breaks installation.
常见错误
错误写法
Forgetting 那个 service 工作者需要 HTTPS (except localhost for development).
正确做法
Service 工作者仅 注册 over HTTPS in production. Use HTTPS for 你的 deployed site (Let's Encrypt provides free certificates). localhost 是 exempt for development. 不使用 HTTPS, service 工作者将 不注册 and PWA 将不 工作.
错误写法
缓存也 aggressively and 从不更新 cached 内容.
正确做法
Version 你的缓存 name (e.g., my-app-v1) and 更新它 当内容更改. Use stale-虽然-revalidate for 数据那个更新频繁地. Listen for 'activate' 事件到 clean 上旧 caches. 否则, 用户 see stale 内容 forever.
相关资源
相关速查表
- JavaScript Cheatsheet
引用 for service 工作者 lifecycle 事件 and 缓存 API.
练习 PWA 基础
2 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。