I wrote a code to filter a list of elements.
HTML:
- France
- Canada
- Argentina
- Portugal
- France
- Canada
Javascript:
function filterAvailable()
{
var filterText = "ca"; //
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
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!
解决方案
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
}
}
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