The following function needs at least 3 seconds to run (on 500 table rows). Is it possible to make this function faster?
function prepareTable() {
var groupIndex = 0;
$("#row tbody tr").each(function(index) {
// each row gets a unique id
// remove default css styles for table rows
// read out hidden value, that stores if row is a group
var group = $(this).attr('id', 'node-'+index).removeClass("odd event").find('td :hidden').attr('value');
// if it is a group, add special styles to row and remember row index
if (group == 'true') {
groupIndex = index;
$(this).addClass('odd').find("td:first")
.mouseenter(function() {
$(this).parent().addClass("swGroupLink");
})
.mouseleave(function() {
$(this).parent().removeClass("swGroupLink");
});
} else {
// make all following rows to children of the previous group found
$(this).addClass('even child-of-node-' + groupIndex);
}
});
}
I suggest two improvements:
DOM ReferencesExample
I added a variable
$thiswhich caches$(this)in your.each()loop. I also added$mytableand$parent.$mytablestores the#rowelement and$parentstores the parent-node from#row. That is because I remove the whole element from the DOM, do the work and re-attach it to the parent.Test environment: http://www.jsfiddle.net/2C6fB/4/
If that is still too slow, you have other options here. First, look if you can split the loop into smaller pieces. You can optimize that like a lot by using
asychronouscallbacks, for instance,setTimeout. That can be a tricky business and I would need to know your code in more detail, but in general you might just want to wrap your whole loop into singlesetTimeout()functions. Example -> http://www.jsfiddle.net/2C6fB/5/This ensures that the browser won’t “hang” while operating. But of course this took a little bit longer to complete the whole task.