1. 程式人生 > >Angular 學習筆記 ( PWA + App Shell )

Angular 學習筆記 ( PWA + App Shell )

https default 重點 通過 監聽 開啟 說了 shel html

PWA (Progressive Web Apps) 是未來網頁設計的方向. 漸進式網站.

Angular v5 開始支持 pwa 網站 (所謂支持意思是說有一些 build in 的方法和規範去實現它) 。

就目前來說 pwa 有幾個特點 :

1.https

2.Service work

3.Cache API

4.攔截 Fetch (任何遊覽器發出的請求, 包括 index.html)

5.Push API

6.Share API

主要的用途是 :

1. offline view (通過 service work + cache + 攔截 fetch 實現)

2. push notification (通過 service work + Push API + Notification API 實現)

3. AMP 網站預加載 service-work.js (在 amp page 出發 service worker 預加載整個頁面需要的 html,js.css)

參考 :

https://blog.angular-university.io/service-workers/

https://blog.angular-university.io/angular-service-worker/

實現我就不說了,人家已經是 step by step 了. 我就講一些重點吧.

service work 比較復雜的地方是 life cycle.

當你訪問一個網站後 www.domain.com

當頁面渲染好後, ng 會找到一個好的時間點去 register service worker 也就是加載 "/ngsw-worker.js".

ng 有自己的方式(比如對比文件的 hash 等等)去管理 life cycle (如果你知道怎麽自己實現 service worker 的話,你會發現 ng 完全自己控制了 life cycle 而沒有使用 default 的)

service work 開啟後, 就是一般的預加載 css, js, html 等等. 然後統統都會 cache 起來.

完成後, 你 offline 就可以看到效果了. 你 refresh 的話會發現所有的請求都是從 cache 返回的,包括 index.html

連 index.html 都 cache 起來了,那要怎樣更新網站呢 ?

每一次更新, ng 在 cli build 的時候都會生產一個 hash 放進 ngsw-worker.js,

網站每一次刷新雖然會先使用 cache 版本,但是它也會馬上去加載 ngsw-worker.js 然後進行判斷看 hash 是否一樣。

如果發現有新的 js,css 那麽就會去加載,等到下一次 refresh 就會使用新版本了. 如果你希望用戶馬上使用新版本, ng 也開放了一個 API

可以通過 subscribe 的方式監聽這個 update event, 然後可以 alert 用戶叫用戶馬上 refresh.

所以流程是 cache first -> check update -> notify user and update now Or wait for user next refresh

我建議在網站比較穩定後才設置 service work, 而

而且網頁必須向後兼容, 或至少要有錯誤處理在版本過久的情況下。

因為不管怎樣,用戶一定會先獲取到 cache 的版本,如果你的 cache 版本運行失敗(比如你的 Ajax response 已經換了, 而之前的 js 版本無法處理, 甚至 error, 這樣用戶可能非常的難升級到新版本,而且體驗也會很糟. 所以要用 pwa 要註意這個哦)

除了 cache, ng 也封裝了 push notification。

之前寫過一篇關於 push 的原生實現.

http://www.cnblogs.com/keatkeat/p/7503615.html

ng 的實現看這個

https://medium.com/google-developer-experts/a-new-angular-service-worker-creating-automatic-progressive-web-apps-part-2-practice-3221471269a1

目前還不支持 notification click 時間,這個還蠻糟糕的,非常重要的功能丫。怎麽會沒有實現呢 ? https://github.com/angular/angular/issues/20956

而且也沒有擴展的方式,如果硬要就需要直接改 ngsw-worker.js 源碼了。

最後說說 App-shell

這個和 skeleton 類似的概念, 取代單調的 loading bar.

step by step : https://blog.angular-university.io/angular-app-shell/

ng 的實現手法是通過 cli build 時運行 server render, 然後把渲染好的 skeleton page 插入到 index.html.

好啦,接下來我會準備做一個簡單的電子商務, 來實戰一個 ng. 會做成一個視屏希望新手們可以省走冤枉路.

Angular 學習筆記 ( PWA + App Shell )