Here is the jQuery/Javascript code I’m using to sort through an unordered list of elements and remove them based on the user’s query:
// event binding for the search filter
$('.search-box').keyup(function(){
var query = $(this).val().toLowerCase(),
length = query.length;
$('.friends-list li').each(function(){
if(query.length > 1 && $(this).find('span').text().toLowerCase().substring(0, length) != query){
$(this).hide();
} else {
$(this).show();
}
});
});
Unfortunately, when I get a large number of li elements, this slows down considerably and sometimes hangs on the system. Is there a way to optimize this, or do all of the searching first and then remove the li elements all at one time so the system does not hang?
When I do a server-side search, I can just have a loading spinner and a success callback, but the same does not seem to apply for the client-side.
A couple of tips
Don’t fire search on each keyup event. Instead, have a short timer (~200ms) that waits for a next keyup and starts searching if there’s none:
If
query.length <=1your loop can be optimized away, no need to check that on each iteration.each(li)...find(span)is too much overhead. Try iterating thru spans directly:Also note some minor optimizations in the above code.