PWA 之Q&A

——吉吉《PWA初窺》學習筆記

Q1:什麼是PWA?
A1: PWA全稱Progressive Web App,即漸進式WEB應用。一個 PWA 應用首先是一個網頁, 可以通過 Web 技術編寫出一個網頁應用. 隨後添加上 App Manifest 和 Service Worker 來實現 PWA 的安裝和離線等功能

Q2: PWA解決了什麼問題?
A2: 1) 可以添加至主屏幕,點擊主屏幕圖標可以實現啓動動畫以及隱藏地址欄
2)實現離線緩存功能,即使用戶手機沒有網絡,依然可以使用一些離線功能
3)實現了消息推送

Q3: App Manifest 是什麼,有什麼用?
A3: Web應用程序清單在一個JSON文本文件中提供有關應用程序的信息(如名稱,作者,圖標和描述)。manifest 的目的是將Web應用程序安裝到設備的主屏幕,爲用戶提供更快的訪問和更豐富的體驗。

Q4: 什麼是service worker,有什麼作用?
A4: Service Worker 是 Chrome 團隊提出和力推的一個 WEB API,用於給 web 應用提供高級的可持續的後臺處理能力。
Service Workers 就像介於服務器和網頁之間的攔截器,能夠攔截進出的HTTP 請求,從而完全控制你的網站。

Q5: service worker 有什麼特點?
A5:1)resource caching and push notifications
2)client-side programmable proxy between web app and the outside world
3)service workers run independent of the application they are associated with
4)the primary uses for a service workers are to act as a caching agent to handle network requests
5)and to store content for offline use and secondly to handle push messaging the
6)information that you need to persist and reuse across restartswork with IndexedDB databases
7)promise-based
8)only available on secure origins(https)

Q6: HTTP緩存與service worker緩存有什麼區別
A6: HTTP緩存
Web 服務器可以使用 Expires 首部來通知 Web 客戶端,它可以使用資源的當前副本,直到指定的“過期
時間”。反過來,瀏覽器可以緩存此資源,並且只有在有效期滿後纔會再次檢查新版本。
使用 HTTP 緩存意味着你要依賴服務器來告訴你何時緩存資源和何時過期。
service worker緩存
Service Workers 的強大在於它們攔截 HTTP 請求的能力
進入任何傳入的 HTTP 請求,並決定想要如何響應。在你的 Service Worker 中,可以編寫邏輯來決定
想要緩存的資源,以及需要滿足什麼條件和資源需要緩存多久。一切盡歸你掌控!
service worker緩存

Q7: service worker的生命週期是怎樣的?
A7: 生命週期

Q8: 怎麼配置一個PWA
A8: 1)準備一個html文件,以及相應的css等:

<head>
  <title>Minimal PWA</title>
  <meta name="viewport" content="width=device-width, user-scalable=no" />
  <link rel="stylesheet" type="text/css" href="main.css">
  <link rel="manifest" href="manifest.json" />
</head>
<body>
  <h3>Revision 1</h3>
  <div class="main-text">Minimal PWA, open Console for more~~~</div>
</body>

2)添加manifest.json文件

{
  "name": "Minimal app to try PWA",
  "short_name": "Minimal PWA",
  "display": "standalone",
  "start_url": "/",
  "theme_color": "#8888ff",
  "background_color": "#aaaaff",
  "icons": [
    {
      "src": "e.png",
      "sizes": "256x256",
      "type": "image/png"
    }
  ]
}

3)添加Service Worker

Service Worker 在網頁已經關閉的情況下還可以運行, 用來實現頁面的緩存和離線, 後臺通知等等功能。sw.js 文件需要在 HTML 當中引入:

<script>
  if (navigator.serviceWorker != null) {
    navigator.serviceWorker.register('sw.js')
    .then(function(registration) {
      console.log('Registered events at scope: ', registration.scope);
    });
  }
</script>

4)處理靜態緩存

var cacheStorageKey = 'minimal-pwa-1'

var cacheList = [
  '/',
  "index.html",
  "main.css",
  "e.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 腳本能立即激活和生效。
5)處理動態緩存
網頁抓取資源的過程中, 在 Service Worker 可以捕獲到 fetch 事件, 可以編寫代碼決定如何響應資源的請求:

self.addEventListener('fetch', function(e) {
  e.respondWith(
    caches.match(e.request).then(function(response) {
      if (response != null) {
        return response
      }
      return fetch(e.request.url)
    })
  )
})

真實的項目當中, 可以根據資源的類型, 站點的特點, 可以專門設計複雜的策略。fetch 事件當中甚至可以手動生成 Response 返回給頁面。
6)更新靜態資源
緩存的資源隨着版本的更新會過期, 所以會根據緩存的字符串名稱(這裏變量爲 cacheStorageKey, 值用了 “minimal-pwa-1”)清除舊緩存, 可以遍歷所有的緩存名稱逐一判斷決決定是否清除:

self.addEventListener('activate', function(e) {
  e.waitUntil(
   Promise.all(
        cacheNames.filter(name => {
          return name !== cacheStorageKey
        }).map(name => {
          return caches.delete(name)
        })
      ).then(() => self.clients.claim())
     })
  )
})

在新安裝的 Service Worker 中通過調用 self.clients.claim() 取得頁面的控制權, 這樣之後打開頁面都會使用版本更新的緩存。舊的 Service Worker 腳本不再控制着頁面之後會被停止。

相關文章:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章