渐进式 Web 应用(Progressive Web App,PWA)是一种结合传统 Web 技术与现代移动应用特性的技术方案,旨在通过 HTML、CSS 和 JavaScript 构建具备原生应用体验的 Web 应用。其核心特性包括:
以下示例架构环境是 vite + react 脚手架。
npm i vite-plugin-pwa -D
import { VitePWA } from 'vite-plugin-pwa'
// https://vite.dev/config/
export default defineConfig({
plugins: [
react(),
VitePWA({
registerType: 'autoUpdate',
workbox: {
globPatterns: ['**/*.{js,css,html}'],
},
manifest: {
name: '源码分享',
short_name: '源码分享',
description: '源码分享',
theme_color: '#000000',
background_color: '#000000',
icons: [
{
src: 'public/logo.svg',
sizes: '192x192',
type: 'image/svg+xml',
},
{
src: 'public/logo.svg',
sizes: '512x512',
type: 'image/svg+xml',
},
],
},
devOptions: {
enabled: true,
type: 'module',
},
}),
],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
})
配置注意:
到此依赖、配置都已经全部完成,是不是非常简单。
首页来分析一下具体需要实现的需求,希望做些什么功能。其实上面配置好,个人觉得90%目的已经达到。能够安装应用,生成一个渐进式 Web 应用(PWA),并缓存关键资源。
下面我们来分析一些高级的运用、体验的优化。
如何引导用户安装PWA应用?
let deferredPrompt = null;
const handleBeforeInstallPrompt = (e) => {
e.preventDefault();
deferredPrompt.current = e;
setIsInstallable(true);
};
window.addEventListener("beforeinstallprompt", handleBeforeInstallPrompt);
const checkDisplayMode = () => {
const isStandalone = window.matchMedia(
"(display-mode: standalone)"
).matches;
const isIOS =
/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
setIsInstalled(isStandalone || (isIOS && navigator.standalone));
};
注意:iOS 不支持 beforeinstallprompt 事件,需通过 navigator.standalone 检测
最后就是如何更好的引导用户安装,这里不多说了,自由发挥自己的引导方式,做更好的ui效果。
完整源码
import { useEffect, useState, useRef } from 'react';
function App() {
const [isInstallable, setIsInstallable] = useState(false);
const [isInstalled, setIsInstalled] = useState(false);
const deferredPrompt = useRef(null);
useEffect(() => {
const handleBeforeInstallPrompt = (e) => {
e.preventDefault();
deferredPrompt.current = e;
setIsInstallable(true);
};
window.addEventListener("beforeinstallprompt", handleBeforeInstallPrompt);
// 当前是否已是pwa离线应用
const checkDisplayMode = () => {
const isStandalone = window.matchMedia(
"(display-mode: standalone)"
).matches;
const isIOS =
/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
setIsInstalled(isStandalone || (isIOS && navigator.standalone));
};
checkDisplayMode();
return () => {
window.removeEventListener(
"beforeinstallprompt",
handleBeforeInstallPrompt
);
};
}, []);
const handleInstall = async () => {
if (deferredPrompt.current) {
deferredPrompt.current.prompt();
const { outcome } = await deferredPrompt.current.userChoice;
if (outcome === 'accepted') {
// 同意
setIsInstallable(false);
deferredPrompt.current = null;
} else {
// 拒绝
console.log("拒绝");
}
}
};
return (
<>
>
);
}
export default App;
最后PWA上线的必须条件:
渐进式 Web 应用(PWA)入门级教程 - 高质量源码分享平台-免费下载各类网站源码与模板及前沿动态资讯