I have a rather large javascript array of objects that I am transforming into an HTML table. Each object in the array looks like:
{
name:'Document Title',
url:'/path/to/document.html',
categories:['Some Category'],
protocols:['ID Number','Another ID'],
sites:['Location']
}
It's possible to have multiple categories, protocols, and sites, hence why they are in arrays.
The jQuery I've written to do the transformation is:
var table = $('<table class="table table-bordered table-condensed table-striped data-table">'),
tbody = $('<tbody>'),
thead = $('<thead><tr><th width="100">Protocol</th><th>Report Name</th><th width="140">Category</th><th width="220">Site</th></tr></thead>');
$.each(reports,function(i,report) {
var tr = document.createElement('tr'),
cellProtocol = document.createElement('td'),
cellName = document.createElement('td'),
cellCategory = document.createElement('td'),
cellSite = document.createElement('td'),
reportLink = document.createElement('a');
// If property doesn't exist, set to empty array
report.protocols = report.protocols || [];
report.sites = report.sites || [];
report.categories = report.categories || [];
reportLink.setAttribute('href',report.url);
reportLink.appendChild(document.createTextNode(report.name));
cellProtocol.appendChild(document.createTextNode(report.protocols.join(', ')));
cellName.appendChild(reportLink);
cellCategory.appendChild(document.createTextNode(report.categories.join(', ')));
cellSite.appendChild(document.createTextNode(report.sites.join(', ')));
tr.appendChild(cellProtocol);
tr.appendChild(cellName);
tr.appendChild(cellCategory);
tr.appendChild(cellSite);
tbody[0].appendChild(tr);
});
$('#report-table').empty().append(table.append(thead,tbody));
It currently takes about 2 seconds to transform 4200 objects into table rows and display the finished table. In the $.each
loop I am using appendChild
as I understand it is faster than using innerHTML
or $.append
.
Are there any improvements here I can make in performance?