ie8加载js太慢_jQuery在IE中非常慢

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值