为什么要减少操作DOM?
下面将按照以下布局同时操作div1和div2;然后在控制台打印出所需的时间,对时间尽心对比;
以下是布局:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<script>
//这里写代码
</script>
</body>
</html>
对div1的操作如下:
console.time("interval1");
var odiv = document.getElementById("div1");
for (var i = 0, str = ""; i < 5000; i++) {
odiv.innerHTML += "a"
}
console.timeEnd("interva11");
这里在div1上连续操作了5000次,计时器interval1;
对div2的操作如下:
console.time("interval2");
var odiv2 = document.getElementById("div2");
for (var i = 0, str = ""; i < 5000; i++) {
str += "a"
}
odiv2.innerHTML = str;
console.timeEnd("interval2");
这里只操作了一次,同样完成了交互效果,计时器interval2;
那么分别用了多久呢?
interva1: 1502944900429.3262ms
interval2: 0.5830078125ms
这就是documentCreateFragment的好处了
也是为什么很多性能优化的书籍中说要减少dom操作额
以下是完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<script>
window.onload = function () {
console.time("interval1");
var odiv = document.getElementById("div1");
for (var i = 0, str = ""; i < 5000; i++) {
odiv.innerHTML += "a"
}
console.timeEnd("interva1");
console.time("interval2");
var odiv2 = document.getElementById("div2");
for (var i = 0, str = ""; i < 5000; i++) {
str += "a"
}
odiv2.innerHTML = str;
console.timeEnd("interval2");
}
</script>
</body>
</html>