一、一個 PWA 應用首先是一個網頁, 能夠經過 Web 技術編寫出一個網頁應用. 隨後添加上 App Manifest 和 Service Worker 來實現 PWA 的安裝和離線等功能。javascript
二、建立HTML文件html
<html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0,viewport-fit=cover"> <meta name="x5-orientation" content="portrait"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="format-detection" content="telephone=no"> <meta name="viewport" content="width=device-width, user-scalable=no" /> <link rel="manifest" href="manifest.json" /> <link rel="apple-touch-icon" href="e.png"/> <title>1v1</title> </head> <body> <div id="main">3</div> <script> if (navigator.serviceWorker != null) { navigator.serviceWorker.register('sw.js') .then(function (registration) { console.log('Registered events at scope: ', registration.scope); }); } </script> <script src="index.js"></script> </body> </html>
三、HTML中有引入manifest.json(名字配置項等內容)、apple-touch-icon(ios顯示圖標)、引入sw.js(增長單機緩存內容等)java
四、manifest.json的大體內容ios
{ "name": "Minimal app to try PWA", \\名字 "short_name": "PWA", \\短名字 "display": "standalone", \\狀態 "start_url": "/pwa/index.html", \\入口 "theme_color": "#8888ff", \\預設主題顏色 "background_color": "#aaaaff", \\預設背景顏色 "icons": [ \\安卓的圖標 { "src": "e.png", "sizes": "256x256", "type": "image/png" } ] }
五、sw.js大體內容web
var cacheStorageKey = 'v2' \\版本號,每次根據這個號是否有修改來決定再替換緩存內容 var cacheList = [ \\緩存內容 "index.html", "index.js", "e.png" ] self.addEventListener('install', e => { \\添加緩存 e.waitUntil( caches.open(cacheStorageKey) .then(cache => cache.addAll(cacheList)) .then(() => self.skipWaiting()) ) }) self.addEventListener('fetch', function (e) { \\再次獲取緩存的回調 e.respondWith( caches.match(e.request).then(function (response) { if (response != null) { return response } return fetch(e.request.url) }) ) }) self.addEventListener('activate', function (e) { \\根據緩存名不一樣獲取內容 e.waitUntil( Promise.all( caches.keys().then(cacheNames => { return cacheNames.map(name => { if (name !== cacheStorageKey) { return caches.delete(name) } }) }) ).then(() => { return self.clients.claim() }) ) })
六、建立index.js測試json
let body = document.getElementsByTagName('body')[0] body.style.backgroundColor='#333'
七、要在前綴是https或者localhost下才能有緩存的內容,每次更新都要先修改一下版本號,也就是sw.js裏的cacheStroageKey的名字緩存