尽可能不要变更高层的DOM元素,而以底层DOM元素的变更代替;再好比,重绘table
布局和flex
布局,开销都会比较大。javascript
var foo = document.getElementById('foobar'); foo.style.color = 'blue'; foo.style.marginTop = '30px';
上面的代码只会致使一次重绘,由于浏览器会累积DOM变更,而后一次性执行。java
提升性能:浏览器
window.requestAnimationFrame()
,由于它能够把代码推迟到下一次重流时执行,而不是当即要求页面重流// 重绘代价高 function doubleHeight(element) { var currentHeight = element.clientHeight; element.style.height = (currentHeight * 2) + 'px'; } all_my_elements.forEach(doubleHeight); // 重绘代价低 function doubleHeight(element) { var currentHeight = element.clientHeight; window.requestAnimationFrame(function () { element.style.height = (currentHeight * 2) + 'px'; }); } all_my_elements.forEach(doubleHeight);