Reputation: 5801
I have an UI scenario which contains a list (<ul>
) with a potential huge number of list items (<li>
). The scenario includes searching, filtering (on classes and attributes), deletion and creation of these items, using jQuery. What are the best practices and optimizations to handle this case? How slow/heavy can be th UI get with a huge number of elements?
Upvotes: 0
Views: 1738
Reputation: 141827
Work with your ul's outside of the DOM by following this pattern:
// Clone the ul
var $the_ul = $('#the_ul');
var $new_ul = $('#the_ul').clone();
// Do stuff to $new_ul
// In this example create 5000 lis
for(var i = 1; i <= 5000; i++){
$new_ul.append($('<li class="li-' + i + '">foo ' + i + ' bar</li>'));
}
// Replace the ul in the dom with the updated one
$the_ul.replaceWith($new_ul);
See this example jsFiddle which creates 5000 lis and then filters them (by class) to only show prime numbers to show how this pattern can be quite efficient and you should run into no problems.
Upvotes: 0
Reputation: 94101
For best performance, work with your objects outside the DOM and avoid excessive reflows by appending everything at last and delegate your events.
$('<li/>', { ... }).appendTo('#el'); // Dynamic object, appended at last
$('ul').on('click', 'li', function(){ ... }); // Delegate events
If you have to work with elements in the DOM, then it's better to detach()
the element or clone()
it, work with it, and append()
it to the DOM again.
Upvotes: 2
Reputation: 6825
To answer your second question somewhat:
var ul = jQuery('<ul/>');
for( var i = 0; i < 100000; i++)
{
var li =jQuery('<li class="hilight"/>');
if( i % 2 == 0 )li.addClass('special');
ul.append(li);
}
jQuery(".special").css("background-color","green");
Was it fast enough?
Upvotes: 0
Reputation: 2481
It is heavy enough when hundreds, not thousands :D
Maybe you should use pagination with or without AJAX .
Upvotes: 0