首先要感谢 EtherDream 的不同观点,在 巧用cssText属性批量操作样式 一篇中由于他的质疑态度使我做了进一步的测试。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="gbk">
<title>事实证明cssText在多数浏览器中性能较高</title>
</head>
<body>
<input type="button" value="测试1" onclick="test1()"/> ||
<input type="button" value="测试2" onclick="test2()"/>
<div id="container"></div>
<script>
var container = document.getElementById('container');
function appendElement(){
var ary = [];
container.innerHTML = '';
for(var i=0;i<=2000;i++){
var div = document.createElement('div');
ary.push(div);
container.appendChild(div);
}
return ary;
}
function test1(){
var ary = appendElement();
var d1 = new Date;
for(var j=0;j<ary.length;j++){
var sty = ary[j].style;
sty.width = '50px';
sty.height = '50px';
sty.backgroundColor = 'gold';
}
var d2 = new Date;
alert('耗时:' + (d2-d1));
}
function test2(){
var ary = appendElement();
var d1 = new Date;
for(var j=0;j<ary.length;j++){
var sty = ary[j].style;
sty.cssText = 'width:50px;height:50px;background-color:red;';
}
var d2 = new Date;
alert('耗时:' + (d2-d1));
}
</script>
</body>
</html>
测试1,测试2都分别添加2000个div到页面上。
测试1 使用以下三行代码
sty.width = '50px';
sty.height = '50px';
sty.backgroundColor = 'gold';
测试2 使用cssText一行搞定
sty.cssText = 'width:50px;height:50px;background-color:red;';
也许你会和我一样听说或认为cssText只reflow一次,相对测试1(reflow 3次)页面渲染性能更高些。事实的确是这样,看测试结果。
IE6 | IE7 | IE8 | IE9 | Firefox | Chrome | Safari | Opera | |
测试1 | 75 | 68 | 28 | 32 | 857 | 31 | 26 | 20 |
测试2 | 47 | 39 | 25 | 24 | 308 | 27 | 17 | 21 |
以上可以看出所有浏览器中当操作多个样式时style.cssText效率还是高于style.width/height/background-color。如果把数量由2000改为5000的话效果将更明显。因此当操作多个样式时更推荐使用cssText。当然以上只是记录一次测试结果,你可以多试两次。为保证每次点击测试的单一性,建议每测一次后刷新下页面。
从以上数据我们可以得到以下结果:
1,IE随着版本的提高,两者的效率越来越接近。
2,Firefox两者的性能差异较大。
3,Chrome/Safari/Opera中的两者性能差异较小,Opera中偶尔测试2的效率要低于测试1。
4,无论测试1,测试2。Firefox的效率都要低于其他浏览器很多,甚至包括IE6。这让人大跌眼镜。
点击这里可以直接测试:
|| ||
相关: