Supercharge Your Website Using PWA: Installable Website What is a PWA? Why use PWA? Getting Started Project using this Implementation Smartsapp Reference Thanks for reading
使用 PWA 增强您的网站:可安装网站
什么是PWA?
为什么要使用PWA?
入门
使用此实现的项目
Smartsapp
参考
感谢阅读
什么是PWA?
渐进式 Web 应用( PWA) 是指经过精心设计的Web 应用,其功能强大(充分利用原生功能)、可靠性高(即使在离线模式下也能运行)且易于安装。这三大支柱使它们拥有如同特定平台应用程序般的体验。
为什么要使用PWA?
渐进式 Web 应用本质上就是 Web 应用程序。通过渐进式增强,现代浏览器可以启用新功能。使用service workers和web app manifest,可以将 Web 应用程序转换为PWA。即使新功能不可用,用户仍然可以获得核心体验。
从上图可以看出,渐进式 Web 应用程序通过提供用户喜爱的 Web 体验,使用最新的 Web 功能带来增强的功能和可靠性PWA,提供了两全其美的效果,渐进式 Web 应用程序允许任何人、在任何地方、在任何设备上使用单一代码库安装您构建的应用程序。
入门
将网站转变为PWA以下要求:
网站本身(通过https或由提供localhost)
manifest.json(提供有关Web 应用程序的信息)
service worker(允许拦截和控制Web 浏览器如何处理其和的脚本。)network requestsasset caching
{"name":"<name of the application>","short_name":"<short name for the application> (can be same as name)","start_url":"<start url for the website>","display":"<display mode for the website>","description":"<description of the application>","background_color":"<color>","theme_color":"<color>","orientation":"<orientation>","icons":[{"src":"<image source>","sizes":"<widthxheight>","type":"image/png"}]}
一个例子manifest.json如下
{"name":"PWA: Installable website","short_name":"Installable PWA","start_url":"index.html","display":"standalone","description":"App for testing PWA features","background_color":"#ffffff","theme_color":"#000000","orientation":"portrait-primary","icons":[{"src":"image/icon-24.png","sizes":"24x24","type":"image/png"},{"src":"image/icon-32.png","sizes":"32x32","type":"image/png"},{"src":"image/icon-48.png","sizes":"48x48","type":"image/png"},{"src":"image/icon-64.png","sizes":"64x64","type":"image/png"},{"src":"image/icon-128.png","sizes":"128x128","type":"image/png"},{"src":"image/icon-256.png","sizes":"256x256","type":"image/png"}]}
constSTATIC_CACHE="static-cache-v1"conststatic_assets=["/","/index.html","/script.js","/image/icon-24.png","/image/icon-32.png","/image/icon-48.png","/image/icon-64.png","/image/icon-72.png","/image/icon-96.png","/image/icon-128.png","/image/icon-256.png",]// storing static assets in cache on service worker installself.addEventListener("install",event=>{event.waitUntil(caches.open(STATIC_CACHE).then(cache=>{cache.addAll(static_assets)}))})// returning static assets from cacheself.addEventListener("fetch",event=>{event.respondWith(caches.match(event.request).then(response=>{returnresponse||fetch(event.request);}))});
我们需要处理该fetch事件以启用安装。
service worker通过在网站中添加以下脚本来启用
<script>if ('serviceWorker'innavigator){navigator.serviceWorker.register('/service-worker.js');}else{console.log("Service worker is not supported");}</script>