Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance for appending large element/datasets to the dom

I am appending large amounts of table row elements at a time and experiencing some major bottlenecks. At the moment I am using jQuery, but i'm open to a javascript based solution if it gets the job done.

I have the need to append anywhere from 0-100 table rows at a given time (it's actually potentially more, but I'll be paginating anything over 100).

Right now I am appending each table row individually to the dom...

loop {
  ..build html str...
  $("#myTable").append(row);
}

Then I fade them all in at once

$("#myTable tr").fadeIn();

There are a couple things to consider here...

1) I am binding data to each individual table row, which is why i switched from a mass append to appending individual rows in the first place.

2) I really like the fade effect. Although not essential to the application I am very big on aesthetics and animations (that of course don't distract from the use of the application). There simply has to be a good way to apply a modest fade effect to larger amounts of data.

(edit) 3) A major reason for me approaching this in the smaller chunk/recursive way is I need to bind specific data to each row. Am I binding my data wrong? Is there a better way to keep track of this data than binding it to their respective tr?


Is it better to apply affects/dom manipulations in large chunks or smaller chunks in recursive functions?

Are there situations where the it's better to do one or the other? If so, what are the indicators for choosing the appropriate method?

like image 747
Derek Adair Avatar asked Dec 20 '10 17:12

Derek Adair


2 Answers

Take a look at this post by John Resig, it explains the benefit of using DocumentFragments when doing large additions to the DOM.

A DocumentFragment is a container that you can add nodes to without actually altering the DOM in any way. When you are ready you add the entire fragment to the DOM and this places it's content into the DOM in a single operation.

Also, doing $("#myTable") on each iteration is really not recommended - do it once before the loop.

like image 176
Sean Kinsey Avatar answered Nov 10 '22 01:11

Sean Kinsey


i suspect your performance problems are because you are modifying the DOM multiple times, in your loop.

Instead, try modifying it once after you get all your rows. Browsers are really good at innerHTML replaces. Try something like

$("#myTable").html("all the rows dom here");

note you might have to play with the exact selector to use, to get the dom in the correct place. But the main idea is use innerHTML, and use it as few times as possible.

like image 38
hvgotcodes Avatar answered Nov 10 '22 02:11

hvgotcodes