Angular 產品開發(fā)中 OnPush 策略最佳實踐
背景
在Angular產品開發(fā)中,隨著功能的增多,項目的性能會變慢。其中一個重要原因就是每次model數據改變時,都會觸發(fā)大量組件的變更檢測。為了解決問題,我們可以應用Onpush策略。
方案
本文參考了大量理論資料,并結合實際項目提出了應用OnPush策略的最佳實踐,供讀者參考。
最佳實踐
1. 盡量在所有組件中應用OnPush策略。
https://ionic.io/enterprise-guide/angular
2. 進行變更檢測一定要有原因,不要隨便進行變更檢測。
https://netbasal.com/a-comprehensive-guide-to-angular-onpush-change-detection-strategy-5bac493074a4
https://www.learnfk.com/question/angular/41364386.html
3. 對一個大型Angular項目應用OnPush策略時,應該先從葉子節(jié)點開始,保證一切工作正常后,再逐級向上應用OnPush策略,直到根節(jié)點組件。
https://stackoverflow.com/questions/52979543/should-i-always-use-changedetectionstrategy-onpush
4. 沒有input參數的組件,也可以應用OnPush策略。
https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/components/cdk/overflow/overflow-container.component.ts https://git.advent.com/projects/TAM/repos/tamalenextgen2/browse/tamaleweb/src/app/widgets/select-window/select-window.component.ts
5. 與值類型input參數不同,引用類型input參數需要為它創(chuàng)建一個新的對象,才能觸發(fā)OnPush變更檢測。
https://zhuanlan.zhihu.com/p/96486260 https://git.advent.com/projects/TAM/repos/tamalenextgen2/browse/tamaleweb/src/app/widgets/html-container/html-container.component.ts https://git.advent.com/projects/TAM/repos/tamalenextgen2/browse/tamaleweb/src/app/widgets/entity-dropdown-item
6. 如果一個組件僅僅依賴于它的input屬性,并且input屬性是observable,那么應該使用async管道來標注該組件需要進行變更檢測。
https://zhuanlan.zhihu.com/p/96486260 https://git.advent.com/projects/TAM/repos/tamalenextgen2/browse/tamaleweb/src/app/widgets/smart-icon/smart-icon.component.ts
7. 為了防止變更檢測錯誤,最好使用不可變對象(immutable objects)和列表(lists)作為input參數在來構建OnPush策略應用程序。
https://mokkapps.de/blog/the-last-guide-for-angular-change-detection-you-will-ever-need/ https://git.advent.com/projects/TAM/repos/tamalenextgen2/browse/tamaleweb/src/app/widgets/timeline/timeline.component.ts
8. 為了提高性能,可以從 Angular 更改檢測周期中分離組件及其子組件。 為此,我們可以使用 ChangeDetectorRef.detach() 方法。
https://timdeschryver.dev/blog/help-angular-to-make-your-application-faster#detach-components-from-the-change-detection
9. 確保從包括 XHR 調用、Timer 和 Event 在內的每個方法中調用 detectChanges 方法。 可以假設 detectChanges 方法負責實際的更改檢測。
https://medium.com/ngconf/simplified-angular-change-detection-e74809ff804d
10. 可以采用lighthouse來記錄應用OnPush策略后web頁面性能提升
https://chrome.google.com/webstore/detail/lighthouse/blipmdconlkpinefehnmjammfjpmpbjk?hl=zh-cn
OnPush案例
1. NG-ZORRO
https://github.com/NG-ZORRO/ng-zorro-antd
2.Angular Material
https://github.com/angular/components/tree/master/src/material
Internationalized and accessible components for everyone. Well tested to ensure performance and reliability.
浙公網安備 33010602011771號