What is better, appending new elements via DOM functions, or appending strings with HTML tags?

后端 未结 6 1126
无人共我
无人共我 2020-11-29 05:34

I have seen a few different methods to add elements to the DOM. The most prevelent seem to be, for example, either

document.getElementById(\'foo\').innerHTM         


        
6条回答
  •  抹茶落季
    2020-11-29 06:08

    Though this is an old thread, one thing that is not mentioned is the while innerHTML can be faster, care should be taken. Using innerHTML will render every child of the modified element, old and new alike. As such, one single innerHTML assignment is faster (slightly) than DOM create/append, but multiple innerHTML will definetly be slower.

    For example:

    for(let i=0; i < 10; i++)
       document.body.innerHTML+='
    some text
    ';

    will be nearly nearly 5x slower than

    let html = '';
    for(let i=0; i < 10; i++)
       html += '
    some text
    '; document.body.innerHTML = html;

    Since innerHTML assignment is letting the browser natively create/append elements, the second methods results in 10 elements being natively created/appended, while the firstmethod results in 55 elements being created/appended (and 45 being destroyed): 1 element created on first loop-iteration, 2 elements created on the second loop-iteration (the original being destroyed), 3 elements created on the third loop-iteration (the previous 2 being destroyed), and so on.

    If you use innerHTML for speed, you must make sure to create the entire html string first before making the innerHTML assignment, such as creating fresh DOM containers/elements. innerHTML, on the other hand, is a performance loser when appending any container with existing childNodes, especially those with large number of childNodes.

提交回复
热议问题