七、window.requestAnimationFrame()

2018-02-24 15:45 更新

七、window.requestAnimationFrame()

有一些JavaScript方法可以調(diào)節(jié)重新渲染,大幅提高網(wǎng)頁性能。

其中最重要的,就是 window.requestAnimationFrame() 方法。它可以將某些代碼放到下一次重新渲染時(shí)執(zhí)行。

function doubleHeight(element) {
  var currentHeight = element.clientHeight;
  element.style.height = (currentHeight * 2) + 'px';
}
elements.forEach(doubleHeight);

上面的代碼使用循環(huán)操作,將每個(gè)元素的高度都增加一倍。可是,每次循環(huán)都是,讀操作后面跟著一個(gè)寫操作。這會(huì)在短時(shí)間內(nèi)觸發(fā)大量的重新渲染,顯然對(duì)于網(wǎng)頁性能很不利。

我們可以使用window.requestAnimationFrame(),讓讀操作和寫操作分離,把所有的寫操作放到下一次重新渲染。

function doubleHeight(element) {
  var currentHeight = element.clientHeight;
  window.requestAnimationFrame(function () {
 element.style.height = (currentHeight * 2) + 'px';
  });
}
elements.forEach(doubleHeight);

頁面滾動(dòng)事件(scroll)的監(jiān)聽函數(shù),就很適合用 window.requestAnimationFrame() ,推遲到下一次重新渲染。

$(window).on('scroll', function() {
window.requestAnimationFrame(scrollHandler);
});

當(dāng)然,最適用的場(chǎng)合還是網(wǎng)頁動(dòng)畫。下面是一個(gè)旋轉(zhuǎn)動(dòng)畫的例子,元素每一幀旋轉(zhuǎn)1度。

var rAF = window.requestAnimationFrame;

var degrees = 0;
function update() {
  div.style.transform = "rotate(" + degrees + "deg)";
  console.log('updated to degrees ' + degrees);
  degrees = degrees + 1;
  rAF(update);
}
rAF(update);
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)