Speed/efficiency of multiple DOM appendChild

前端 未结 1 1690
广开言路
广开言路 2020-12-06 19:38

I have to create seven div elements in one hit - container A which contains A1, A2, A3 & A4, and then A2a & A2b within A2. I am using multiple calls to this little f

相关标签:
1条回答
  • 2020-12-06 19:58

    You could just use .innerHTML. An alternative would be to use a document fragment:

    var fragment = document.createDocumentFragment();
    
    function u1(t, i, c){ // type,id,class_name
        var tag = document.createElement(t); // Create node to be appended
        tag.id = i;
        tag.className = c;
        fragment.appendChild(tag); // will use `fragment` from the outer scope
    }
    
    // call u1() seven times
    
    // then insert all the elements into the DOM all at once
    document.getElementById('foo').appendChild(fragment);
    

    Document fragments are a bit slow to create, but can save performance in the long run. In this case, for example, you go from 7 DOM insertions to just one. (Anything involving the DOM is slow in JavaScript.)

    If you want to benchmark your specific use case using both approaches, create a jsPerf test case.

    0 讨论(0)
提交回复
热议问题