javascript中级--文档碎片
一、普通插入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
window.onload = function() {
var oBtn = document.getElementById('btn1');
var oUl = document.getElementById('ul1');
oBtn.onclick = function() {
var iStart = new Date().getTime();
var i = 0;
for (i = 0; i < 100000; i++) {
var oLi = document.createElement('li');
oUl.appendChild(oLi);
}
alert(new Date().getTime() - iStart); //302 313 345
}
}
</script>
</head>
<body>
<input id="btn1" type="button" name="" value="普通插入">
<ul id="ul1">
</ul>
</body>
</html>
二、文档碎片插入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
window.onload = function() {
var oBtn = document.getElementById('btn1');
var oUl = document.getElementById('ul1');
oBtn.onclick = function() {
var iStart = new Date().getTime();
var oFrag = document.createDocumentFragment(); //文档碎片
var i = 0;
for (i = 0; i < 100000; i++) {
var oLi = document.createElement('li');
oFrag.appendChild(oLi);
}
oUl.appendChild(oFrag);
alert(new Date().getTime() - iStart); //279 340 291
}
}
</script>
</head>
<body>
<input id="btn1" type="button" name="" value="碎片插入">
<ul id="ul1">
</ul>
</body>
</html>

浙公网安备 33010602011771号