Johan
Johan

Reputation: 35213

Slow script in IE7 - fastest jquery selector

$.each(data, function (i, val) {
                        $(':checkbox.' + i).prop('checked', (val == 1 ? true : false));
                        $(':text.' + i + ', select.' + i).val(val);
                    });

data is a JSON-object. IE7 cries about a slow script when i run this. Im mapping values from the json object to the classname, "i". Is there any way to make this selector run faster? The code works, but the speed of iterating thorugh every element must be faster to get rid of the ie7 slow script message. Thanks

Upvotes: 1

Views: 1059

Answers (3)

CedX
CedX

Reputation: 3987

Some tips:

  • .prop() is in general slower than .attr()
  • narrow your selectors: ":checkbox" and ":text" only applies to inputs

    $('input:checkbox.'+i).attr('checked', Boolean(val));
    $('input:text.'+i+', select.'+i).val(val);

Upvotes: 0

gotofritz
gotofritz

Reputation: 3381

Can you narrow it down to a parent? I.e., are these elements inside a form, a div, etc you can start from?

var $memoized_form = $( 'form#the_form' );

$.each(data, function (i, val) {
    $memoized_form.find( 'input:checkbox.' + i ).prop('checked', (val == 1 ? true : false));
    $memoized_form.find( 'input:text.' + i + ', select.' + i).val(val);
});

Upvotes: 0

csharpnumpty
csharpnumpty

Reputation: 3723

Don't use pseudo selectors without a container or narrowed context, they're slow and particularly bad in IE7 or IE8 compat mode in my experience.

Switch the $(":etc") syntax with $("#container").find("input:text") and try replacing the $.each with a traditional for loop (Assuming the $.each is iterating a lot of things, otherwise the impact is negligable)

cache the container outside the loop too.

var $container = $("#container");
$.each (etc, function(i) {
      var a = $container.find("input:text");
      // do more stuff
}

Some markup might provide me with an opportunity to be a little more specific

Upvotes: 1

Related Questions