ItayM
ItayM

Reputation: 912

parallel option in .each() jquery

I have jquery app, in the page I have about 1500 checkboxs. I did search text box for filter and hide the not relevant lines.Its work.. but.. the problem is that It takes a lot of time (over 20 seconds). my code is:

 $('#tb_values').keyup(function () { 
        $("#div_values input").each(
            function () {                 
                var value_a = $(this).attr('value');                   
                var tb_text = $('#tb_values').val();
                if (value_a.indexOf(tb_text, 0) == -1) {
                    $(this).parent().hide();
                }
                else {
                    $(this).parent().show();
                }
            });        

});

How can I do it in Parallel way \ Faster way? Thanks

Upvotes: 1

Views: 2683

Answers (2)

pxx
pxx

Reputation: 258

You have a performance issue. Each iteration causes repaint, reflow/relayout of probably the full page. You should find another approach which will cause redraw only once. I don't see the full picture so I can just guess. It could be something like this:

var html = '';
$("#div_values input").each(function () {  
    var $this = $(this);
    var value_a = this.value;  
    if (value_a.indexOf(tb_text) == -1) {
        html += '<div class="hidden"><input type="radio" ... /></div>';
    }
    else {
        html += '<div class="visible"><input type="radio" ... /></div>';
    }
});
$('#div_values').html(html);

This approach is very fast, but has couple of cons:

  1. You need a separate function for recreating this structure and recreate it on almost every change.
  2. All event handlers and custom data on generated elements will be lost.

Also you can try to clone your container, do the same operations on cloned structure and only after that replace it with a new one.

var currentInstance = $('#div_values');
var clonedInstance = currentInstance.clone();
clonedInstance.find('input').each(...);
currentInstance.after(clonedInstance);
currentInstance.remove();

It should work good, but not so fast as .html(...)

As well you can take a look on documtFragments.

Upvotes: 3

Sushanth --
Sushanth --

Reputation: 55740

Maybe try caching some of the selectors and use native methods if possible.

$('#tb_values').keyup(function () { 
        var tb_text = $('#tb_values')[0].value;
        $("#div_values input").each(
            function () {  
                var $this = $(this);               
                var value_a = this.value;  
                if (value_a.indexOf(tb_text) == -1) {
                    $this.parent().hide();
                }
                else {
                    $this.parent().show();
                }
            });        

});

Upvotes: 0

Related Questions