jQuery very slow in IE

2019-01-28 23:05发布

问题:

I wrote a code to filter a list of elements.

HTML:

<div id="ms-simpleCountries" class="ms-container">
<div class="ms-selectable"><ul><li style="display: none;" ms-value="fr">France</li><li style="display: none;" ms-value="ca">Canada</li><li ms-value="ar">Argentina</li><li ms-value="pt">Portugal</li></ul></div>
<div class="ms-selection"><ul><li ms-value="fr">France</li><li ms-value="ca">Canada</li></ul></div>
</div>

Javascript:

function filterAvailable()
{
var filterText = "ca"; // <-- string used to filter


var a_val;
var a_txt;
$('.ms-container .ms-selectable li').each (function () { 

    // valore elemento disponibile corrente
    a_val = $(this).attr('ms-value');   // ca
    a_txt = $(this).text();             // canada

    // --
    if ($('.ms-container .ms-selection [ms-value="' +a_val +'"]').length > 0)
    {
        $(this).hide();
    }
    else 
    {
        if ($(this).text().toUpperCase().indexOf(filterText) >= 0)
        {
            $(this).show();
        }
        else
        {
            $(this).hide();
        }
    }

});//each

}//end

I tested this javascript code with about 500 <li> elements in class 'ms-selectable'. In my IE8 this code run in 10000ms, while in FF this run in 1000ms! How to perform this task in IE?

Thanks!

回答1:

Loops, particularly those in which you're interacting with the DOM, are generally likely to cause a performance hit in older browsers. You can help matters by ensuring your selectors are more optimised as Non-Stop Time Travel suggests. Instead of repeating $(this) over and over, cache the element in a variable:

var $this = $(this);

Also, you can generally gain quite a big boost in performance by using a regular "for" loop as opposed to jQuery's $.each() method:

function filterAvailable () {
    var filterText = 'ca';
    var items = $('.ms-container .ms-selectable li');
    var $currentItem;
    var a_val;
    var a_txt;

    for (var i = 0, j = items.length; i < j; i++) {
        $currentItem = $(items[i]); // in place of $(this)

        // Contents of $.each() loop here
    }
}

Lots of tests to support this on jsPerf: http://jsperf.com/jquery-each-vs-for-loop/186

It's important to remember that any DOM interaction, including lookups, is slow. This is especially true when your page has a lot of markup in it. You can speed things up by using IDs, caching your selectors, minimising DOM interaction and using regular for loops. Here's a great roundup from Nicholas Zakas: http://jonraasch.com/blog/10-javascript-performance-boosting-tips-from-nicholas-zakas