js中用事实证明cssText性能高的问题

2019-12-24,,,

复制代码 代码如下:
<!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;height: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;height:50px;background-color:red;';


测试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;height:50px;background-color:red;';

测试代码:

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

您可能感兴趣的文章:

  • JS 字符串连接[性能比较]
  • javascript 三种数组复制方法的性能对比
  • 数组方法解决JS字符串连接性能问题有争议
  • JS 网站性能优化笔记
  • js性能优化 如何更快速加载你的JavaScript页面
  • JavaScript执行效率与性能提升方案
  • web性能优化之javascript性能调优
  • js的压缩及jquery压缩探讨(提高页面加载性能/保护劳动成果)
  • JavaScript提高性能知识点汇总

《js中用事实证明cssText性能高的问题.doc》

下载本文的Word格式文档,以方便收藏与打印。