if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('worker.js').then(function(registration) {
console.log('Worker registration successful', registration.scope);
}, function(err) {
console.log('Worker registration failed', err);
}).catch(function(err) {
console.log(err);
});
});
} else {
console.log('Service Worker is not supported by browser.');
}
现在使用Lighthouse重新审核您的应用程序,您会注意到应用程序性能的提高。
第5步 - 添加飞溅图标
您需要添加一个512x512图标才能显示在启动画面上。为此,您将不得不更新manifest.json并添加图标t0公用文件夹。
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": "/",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
此外,使用以下元标记允许浏览器识别您的应用是PWA。
< meta name = “mobile-web-app-capable” content = “yes” >
< meta name = “apple-mobile-web-app-capable” content = “yes” >
第6步 - 部署PWA
现在,只有HTTPS丢失,并且可以在部署应用程序后修复缓存。在worker.js文件中用'true'更新doCache标志。在Firebase控制台中创建一个新项目并将其命名为“Pwa App”。然后在项目目录中运行以下命令:
npm install -g firebase-tools
firebase login
firebase init
你的firebase.json应该是这样的:
{
"hosting": {
"public": "build",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
初始化后,构建并部署您的应用程序。
- npm run build
- firebase deploy
在使用已部署的URL上的Lighthouse来审核应用后,您将看到以下结果。
![使用React.js开发渐进式Web应用程序的分步教程](http://p2.ttnews.xyz/loading.gif)
最后,您已经使用React.js创建了您的第一个渐进式网络应用程序!
閱讀更多 愛碼農 的文章