Reputation: 151
I have a JSON array which has 9000 records and it is displayed using list li. The HTML object is created using jQuery :
$j.each(DTOList, function(index,obj) {
var $li = $j("<li/>");
var $button = $j("<button/>", { type: "button" , onClick:"location.href='playfile.html?messageId="+obj.id+"&operation=play&to="+obj.to+"&from="+obj.from+"'" });
var $parentDiv = $j("<div/>", { class: "buttonMargin" });
var $numDiv = $j("<div/>", { class: "num" ,text:obj.to});
var $nameDiv = $j("<div/>", { class: "name" ,text:obj.from});
var $timeDiv = $j("<div/>", { class: "time" , text:obj.time});
$parentDiv.append($numDiv);
$parentDiv.append($nameDiv);
$parentDiv.append($timeDiv);
$parentDiv.append($j("<hr>"));
$j("#datalist").append($li.append($button.append($parentDiv)));
});
Here is an example of li created by the above code:
<li>
<button type="button"
onclick="location.href='playfile.html?messageId=1165484222&operation=play&to=Fax Line&from=abc'">
<div class="buttonMargin">
<div class="num">Fax Line</div>
<div class="name">def</div>
<div class="time">Jan 04,2018 12:02:44 AM</div>
<hr>
</div>
</button>
<li>
The problem here is, the above code takes at least 1.5 mins to load and till then my HTML page is blank. Is there any way to improve the above code to increase performance?
Upvotes: 1
Views: 111
Reputation: 634
Likely the main problem here is the DOM operation performed in this line
$j("#datalist").append($li.append($button.append($parentDiv)));
triggering document reflows over and over....
So as a first improvement try to generate all items first (without appending it into the DOM) and then append them afterwards with one single operation.
Something like this:
var elements = [];
$j.each(DTOList, function(index,obj) {
.....
elements.push($li);
});
$j("#datalist").append(elements);
Upvotes: 1
Reputation: 3538
Look at this performance test. Use for
loop instead of .each()
function.
Upvotes: 1