示例
<body>
<div id="div"></div>
<button id="btn1">innerHtml</button>
<button id="btn2">createElement</button>
<script>
btn1.onclick = () => {
console.time('btn1');
let strHtml = '';
for (let i = 0; i < 10000; i++) {
strHtml += `<p>hello world ${i} innerHtml</p>`;
}
div.innerHTML = strHtml;
console.timeEnd('btn1');
}
btn2.onclick = () => {
console.time('btn2');
const fragment = document.createDocumentFragment();
for (let i = 0; i < 10000; i++) {
const p = document.createElement('p');
const text = document.createTextNode(`hello world ${i} createHtml`);
p.appendChild(text);
fragment.appendChild(p);
}
div.appendChild(fragment);
console.timeEnd('btn2');
}
</script>
</body>
chrome性能报告
总结
innerHtml在渲染和加载方面耗时都会大于createElement 因为inenrHtml需要js引擎把字符串转换成字符流,然后通过解析器生成tokens然后生成节点 这些都是会消耗性能的 而createElement性能会更好,因为直接创建出来的就是一个DOM节点对象