改進渲染效能範例 2 - Newsticker

使用 Newsticker 作為改進渲染效能的範例,以下列出需要改進之處與解法,並附上測試結果。

瀏覽器渲染效能(Browser Rendering Performance)

圖片來源:Browser Rendering – Performance past the first page load

改善前

明顯卡卡和怪怪的。

改善前

點此看原始碼和 Demo。

下圖是目前 Timeline 的效能部份。

Newsticker Timeline Performance

要改善的地方

目標

改善中

本範例沒有 Forced Synchronous Layout(FSL)Layout Thrashing 的問題。

繼續往下看。

requestAnimationFrame

使用 requestAnimationFrame 取代 setInterval,讓瀏覽器依照自身狀況優化動畫效能。

點這裡看此功能完整修改。

移除不必要的 DOM Element 操作 + 改用觸發 Composite 的指令

新增和刪除 DOM Element 是主要的效能瓶頸,這一段的畫面更新頻率是 4fps。

$next = $frame.find('.current').next().addClass('current');
$current.removeClass('current').clone().appendTo($frame).remove();
$frame.css('top', startPos + 'px');

使用 transform 改寫。

$frame.css({
  transform: `translateY(-${targetHeight}px)`,
});

更新後接近或超過 60fps。

Performance Timeline

點這裡看此功能完整修改。

will-change

讓合成這個階段的工作,集中在 newsticker 的內容區塊,同時也避免其他區域的繪製連動到這一塊。

Paint flashing

will-change

改善方式是在 ui-newsticker 上加上 will-change,即可消除繪製階段、減少合成的成本。

will-change

點這裡看此功能完整修改。

改善後

改善後

點此看原始碼和 Demo。


關鍵轉譯路徑 效能調校 轉譯效能 Rendering Performance Critical Rendering Path Chrome DevTools will-change requestAnimationFrame css css3 animations 前端效能 系列文

Summer Tang
Sponsored
Summer Tang 一對一諮詢
Summer|TSMC 主任工程師|擁有 15 年資深 Web 架構經驗,職涯歷經跨國頂尖企業與新創。專精於高流量企業級應用開發,核心技術涵蓋微前端、效能優化、測試自動化與 SEO。曾出版多本技術著作,並多次擔任 MOPCON、WebConf 等大型技術年會講者。
了解更多 →