用事实证明cssText性能高
时间:2011-03-13 来源:snandy
首先要感谢 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<=1000;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++){
ary[j].style.width = '50px';
ary[j].style.height = '50px';
ary[j].style.backgroundColor = 'gold';
}
var d2 = new Date;
console.log('耗时:' + (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;background-color:red;';
}
var d2 = new Date;
console.log('耗时:' + (d2-d1));
}
</script>
</body>
</html>
测试1,测试2都分别添加1000个div到页面上。
测试1 使用以下三行代码
ary[j].style.width = '50px'; ary[j].style.height = '50px'; ary[j].style.backgroundColor = 'gold';
测试2 使用cssText一行搞定
sty.cssText = 'width:50px;background-color:red;';
也许你会和我一样听说或认为cssText只reflow一次,相对测试1(reflow 3次)页面渲染性能更高些。事实的确是这样,看测试结果。
| IE8 | Firefox | Safari | Chrome | Opera | |
| 测试1 | 47 | 457 | 23 | 42 | 24 |
| 测试2 | 31 | 179 | 15 | 28 | 17 |
以上可以看出所有浏览器中当操作多个样式时style.cssText效率还是高于style.width/height/background-color。如果把数量由1000改为10000的话效果将更明显。因此当操作多个样式时更推荐使用cssText。
当然以上只是记录一次测试结果,你可以多试两次。但结果都是测试2效率要高
点击这里可以直接测试:
|| ||相关:
巧用cssText属性批量操作样式
相关阅读 更多 +










