PWA 简单实现
一個(gè) PWA 應(yīng)用首先是一個(gè)網(wǎng)頁(yè), 可以通過(guò) Web 技術(shù)編寫(xiě)出一個(gè)網(wǎng)頁(yè)應(yīng)用. 隨后添加上 App Manifest 和 Service Worker 來(lái)實(shí)現(xiàn) PWA 的安裝和離線等功能。
?簡(jiǎn)單的
index.html
<!doctype html> <html lang="en"> <head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width"><title>點(diǎn)聚合</title><link rel="manifest" href="manifest.json" /><link rel="stylesheet" href="index.css"><script>console.log(navigator)if(navigator.serviceWorker != null) {console.log(111)navigator.serviceWorker.register('sw.js').then((registration) => {console.log('registration events at scope ', registration.scope)})} else {console.log(222)}</script><style>html, body, #container {height: 100%;width: 100%;}.input-card {width: 25rem;}.input-card .btn {width: 7rem;margin-right: .7rem;}.input-card .btn:last-child {margin-right: 0;}</style> </head> <body> <div id="container" class="map" tabindex="0"><h1>pwd 簡(jiǎn)單實(shí)現(xiàn) F12 大家調(diào)試模式</h1><h2></h2> </div> </body> </html> </html>?
?
sw.js
?
/* self: 表示 Service Worker 作用域, 也是全局變量 caches: 表示緩存 skipWaiting: 表示強(qiáng)制當(dāng)前處在 waiting 狀態(tài)的腳本進(jìn)入 activate 狀態(tài) clients: 表示 Service Worker 接管的頁(yè)面 */ const cacheStorageKey = "minimal-pwa-03"const cacheList = ['/',"index.html","index.css","icon.png" ] // 借助 Service Worker, 可以在注冊(cè)完成安裝 Service Worker 時(shí), 抓取資源寫(xiě)入緩存: self.addEventListener("install", e => {e.waitUntil(caches.open(cacheStorageKey).then(cache => cache.addAll(cacheList)).then(() => self.skipWaiting)) }) // 調(diào)用 self.skipWaiting() 方法是為了在頁(yè)面更新的過(guò)程當(dāng)中, 新的 Service Worker 腳本能立即激活和生效 // 網(wǎng)頁(yè)抓取資源的過(guò)程中, 在 Service Worker 可以捕獲到 fetch 事件, 可以編寫(xiě)代碼決定如何響應(yīng)資源的請(qǐng)求: self.addEventListener('fetch', function(e) {e.respondWith(caches.match(e.request).then(function(response) {console.log('動(dòng)態(tài)緩存處理', response)if (response != null) {return response}return fetch(e.request.url)})) })// 更新靜態(tài)資源self.addEventListener('activate', (e) => {e.waitUntil(Promise.all(caches.filter(name => {return name !== cacheStorageKey}).map(name => {return caches.delete(name)})).then(() => self.clients.claim())) })// 在新安裝的 Service Worker 中通過(guò)調(diào)用 self.clients.claim() 取得頁(yè)面的控制權(quán), 這樣之后打開(kāi)頁(yè)面都會(huì)使用版本更新的緩存。舊的 Service Worker 腳本不再控制著頁(yè)面之后會(huì)被停止?
源碼地址?
https://gitee.com/liuyuquancode/pwa-demo.git
緩存的資源隨著版本的更新會(huì)過(guò)期, 所以會(huì)根據(jù)緩存的字符串名稱(這里變量為 cacheStorageKey, 值用了 "minimal-pwa-1")清除舊緩存, 可以遍歷所有的緩存名稱逐一判斷決決定是否清除(備注: 簡(jiǎn)化的寫(xiě)法, Promise.all 中 return undefined 可能出錯(cuò), 見(jiàn)評(píng)論):
?
http://www.yklove.com/
?
?
?
?
?
總結(jié)
- 上一篇: 声学计算机软件,《声学设计软件EASE及
- 下一篇: 【四足机器人】强化学习实现minitau