PWA 简单实现
一個 PWA 應用首先是一個網頁, 可以通過 Web 技術編寫出一個網頁應用. 隨后添加上 App Manifest 和 Service Worker 來實現 PWA 的安裝和離線等功能。
?簡單的
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>點聚合</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 簡單實現 F12 大家調試模式</h1><h2></h2> </div> </body> </html> </html>?
?
sw.js
?
/* self: 表示 Service Worker 作用域, 也是全局變量 caches: 表示緩存 skipWaiting: 表示強制當前處在 waiting 狀態的腳本進入 activate 狀態 clients: 表示 Service Worker 接管的頁面 */ const cacheStorageKey = "minimal-pwa-03"const cacheList = ['/',"index.html","index.css","icon.png" ] // 借助 Service Worker, 可以在注冊完成安裝 Service Worker 時, 抓取資源寫入緩存: self.addEventListener("install", e => {e.waitUntil(caches.open(cacheStorageKey).then(cache => cache.addAll(cacheList)).then(() => self.skipWaiting)) }) // 調用 self.skipWaiting() 方法是為了在頁面更新的過程當中, 新的 Service Worker 腳本能立即激活和生效 // 網頁抓取資源的過程中, 在 Service Worker 可以捕獲到 fetch 事件, 可以編寫代碼決定如何響應資源的請求: self.addEventListener('fetch', function(e) {e.respondWith(caches.match(e.request).then(function(response) {console.log('動態緩存處理', response)if (response != null) {return response}return fetch(e.request.url)})) })// 更新靜態資源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 中通過調用 self.clients.claim() 取得頁面的控制權, 這樣之后打開頁面都會使用版本更新的緩存。舊的 Service Worker 腳本不再控制著頁面之后會被停止?
源碼地址?
https://gitee.com/liuyuquancode/pwa-demo.git
緩存的資源隨著版本的更新會過期, 所以會根據緩存的字符串名稱(這里變量為 cacheStorageKey, 值用了 "minimal-pwa-1")清除舊緩存, 可以遍歷所有的緩存名稱逐一判斷決決定是否清除(備注: 簡化的寫法, Promise.all 中 return undefined 可能出錯, 見評論):
?
http://www.yklove.com/
?
?
?
?
?
總結
- 上一篇: 声学计算机软件,《声学设计软件EASE及
- 下一篇: 【四足机器人】强化学习实现minitau