昨天我們談到如何幫後端減輕壓力、減少網路請求,今天我們會聚焦在瀏覽器渲染,也就是前端如何讓畫面更新更流暢、減少卡頓
瀏覽器在顯示網頁時,會經歷幾個階段:
(前面Day5 DOM那篇文章也有稍稍提到)
因為Reflow 和 Paint 這些 DOM操作太頻繁,因此運算很耗費資源
減少 Reflow 與 Repaint
Lazy Load
圖片 / 視頻等真的用到的時候再載入
<img loading="lazy">
(預設使用eager
,無論圖片位於網頁上的哪個位置,都會載入)IntersectionObserver
(用於監聽目標元件在畫面上出現或離開的時機),只在使用者看到的時候才載入,同時也減輕main thread 負擔(因為本來如果要偵測有沒有超出viewport應該就是用事件監聽loop去執行 Element.getBoundingClientRect() 之類的方法)減少初次渲染與Windowing
減少 Repaint 範圍
will-change
https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Performance
https://ithelp.ithome.com.tw/articles/10272251
https://web.dev/articles/browser-level-image-lazy-loading?hl=zh-tw
https://ithelp.ithome.com.tw/articles/10271764
https://developer.mozilla.org/zh-CN/docs/Web/CSS/will-change