css3 有一個屬性 will-change,是用來增加 CSS 變化時的效能的,在使用上有幾點要先注意:
- 不要將太多元素設定 will-change,這樣瀏覽器會嘗試優化所有元素而消耗過多的機器資源,反而使網頁變得更慢。
- 在適當的時機加上 will-change。若我們一開始就在 stylesheet 對元素加上 will-change ,會導致瀏覽器一直對此元素做優化而消耗資源,我們應該適時的使用 script 等方式適當的加入、移除 will-change 屬性。
- 不要太早使用 will-change,如果本來網頁就很順暢,多加的 will-change 反而會造成記憶體的消耗及衍生效能問題。
- 給予足夠時間預先加入 will-change 屬性,舉例來說不要在 :hover 或 :active 等觸發後才產生的設定上設置,瀏覽器會來不及反應。
這個屬性有 4 個值可以使用,包含:
- auto: 沒有特定設置屬性而讓瀏覽器去判斷
- scroll-position: 當網頁捲動時預期會發生動畫時的設定
- contens: 當內容會變化時
- <custom-indent>: 自訂希望可以優化的屬性,比如 transform, opacity... 等
示範:
.sidebar {
will-change: transform;
}
以下是比較好的搭配 js 使用的 will-change 的範例:
var el = document.getElementById('element');
// 當滑鼠游標移到目標上給予 will-change 屬性
el.addEventListener('mouseenter', hintBrowser);
// 當 CSS 動畫結束後清除 will-change 屬性
el.addEventListener('animationEnd', removeHint);
function hintBrowser() {
// 填上你預期會在 CSS 動畫中發生改變的 CSS 屬性
this.style.willChange = 'transform, opacity';
}
function removeHint() {
this.style.willChange = 'auto';
}