.append VS .html VS [removed] performance

前端 未结 7 1663
星月不相逢
星月不相逢 2020-11-28 21:16

This site\'s run a test between the 3 different methods and it seems .html is the fastest, followed by .append. followed by .innerHTML

7条回答
  •  醉酒成梦
    2020-11-28 21:43

    I also had a problem with big table redraw (about 10x100 size). It takes about 300ms to redraw whole table.

    The reason was not in the jQuery.append() and not in dom.innerHTML, but in appending each element each time.

    The fastest way is to concatenate all elements html code and then append it to DOM. Like this:

    function redrawMyTable( myData )
    {
        var innerHTML = '';
        for ( var i = 0; i < myData.length; i++ )
        {
          innerHTML += createRowFromData( myData[i] );
        }
    
        myTableTbody.innerHTML = innerHTML;
    }
    function createRowFromData( rowData )
    {
        var rowHTML = '';
        for ( var i = 0; i < rowData.length; i++ )
        {
          rowHTML += createCellFromData( rowData[i] );
        }
        return rowHTML;
    }
    function createCellFromData( cellData )
    {
        //Do everything you need, and return HTMl code as a string
        return cellHTML;
    }
    

    Now it takes only 20-30 ms (against 300ms :))

提交回复
热议问题