1

I have a JSON object 2D associative array (?) created using PapaParse (the data object has 193 lines and 49 columns). I want to dynamically add it to my web page. The code below uses jQuery and works but is very slow. Is there a faster way?

Note: I've given the cells unique IDs because I want the user to be able to choose, interactively, certain columns to keep...

$('<table/>', {
          'id' : 'dataTable' 
    }).appendTo("body");

$('<tbody/>', {
        "id": "dataTableBody",
    }).appendTo("#dataTable");  


// cycle through values and add data to table

for (var i = 0; i < Parseddata.length; i++) {
    $('<tr/>', { 
        "id":"dataTableRow_"+i 
        }).appendTo("#dataTableBody");
    for (var j = 0; j < Parseddata[0].length; j++) {
        $('<td/>', {
            "id":"dataTableColumn_"+j,
            "text":Parseddata[i][j]
      }).appendTo("#dataTableRow_"+i).css({"border":"solid white 1pt"});
    };
};

1 Answer 1

1

I think the fastest way will be is to use html concatenations to generate the entire markup, then append it to the body.

But in the mean time you can delay the rendering of the table to the body till the entire table is constructed so that the redraw of the browser will not be triggered... so try

var $table = $('<table/>', {
    'id': 'dataTable'
});

var $tbody = $('<tbody/>', {
    "id": "dataTableBody",
}).appendTo($table);


// cycle through values and add data to table
var $tr;
for (var i = 0; i < Parseddata.length; i++) {
    $tr = $('<tr/>', {
        "id": "dataTableRow_" + i
    }).appendTo($tbody);
    for (var j = 0; j < Parseddata[0].length; j++) {
        $('<td/>', {
            "id": "dataTableColumn_" + j,
                "text": Parseddata[i][j]
        }).appendTo($tr).css({
            "border": "solid white 1pt"
        });
    };
};

$table.appendTo("body");

A string concatenation like below also can be tried

var html = [];
html.push('<table id="dataTable">');
html.push('<tbody id="dataTableBody">');

// cycle through values and add data to table
var $tr;
for (var i = 0; i < Parseddata.length; i++) {
    html.push('<tr id="dataTableRow_' + i + '">');
    for (var j = 0; j < Parseddata[0].length; j++) {
        html.push('<td id="dataTableColumn_' + i + '_' + j + '">');
        html.push(Parseddata[i][j]);
        html.push('</td>');
    };
    html.push('</tr>');
};

html.push('</tbody>');
html.push('</table>');

$('body').append(html.join(''))


Benchmark: JSPERF

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.