简单使用PWA技术

PWA,Progressive Web App(渐进式web应用),PWA技术可以将web应用具备接近原生应用的特性和用户体验,无需额外安装,支持离线缓存,消息推送等功能 PWA由Service Worker,Promise,fetch,cache Api,Notification Api等技术组成 Service Worker:服务工作线程,独立于主线程,常驻内存,代理网络请求,依赖HTTPS通信 注册Service Worker navigator.serviceWorker.register('./sw.js',{scope: '/'}).then( registration => { console.log(registration) },error => { console.error(error) } ) window.onload = function() { document.body.append('PWA!') } sw.js const cachename = 'v1' self.addEventListener('install', function (event) { console.log('install',event) // 安装新的Service Worker脚本时触发,只有Service Worker脚本不同,会认为是不同的Service Worker版本 event.waitUntil(new Promise(resolve =>{ setTimeout(resolve, 1000) // 安装新的Service Worker脚本后等待1秒后激活该脚本 })) // event.waitUntil(self.skipWaiting) // 强制停止老的Service Worker,激活启动新的Service Worker,只要有更新就激活新的 event.waitUntil(caches.open(name).then(cache =>{ cache.addAll([ '/', './1.img' ]) })) // 开启cache api缓存系统 }) self....

2022-10-28 · 1 min · Me