jQuery绑定效率

我在使用多个jQuery绑定数千个元素和输入时遇到加载速度问题,有没有更有效的方法呢?

该站点具有通过ajax调用在产品列表之间切换的能力,页面无法刷新。 有些列表有10个项目,大约100个,有些超过2000个。当我开始在列表之间翻转时,出现速度问题; 每次加载2000+项目列表时,系统拖动大约10秒钟。

在重建列表之前,我将目标元素的html设置为”,并取消绑定下面的两个绑定。 我确定它与我在回调中所做的所有父,子,和子调用有关。 任何帮助深表感谢。

循环2500次

  • PROD-CODE
  • ...
  • PRICE

结束循环

 $('li.product-code').bind( 'click', function(event){ selector = '#p-'+ $(this).prev('li').children('input').attr('lm'); $(selector).val( ( $(selector).val() == '' ? 1 : ( parseFloat( $(selector).val() ) + 1 ) ) ); Remote.Cart.lastProduct = selector; Remote.Cart.Products.Push( Remote.Cart.customerKey, { code : $(this).prev('li').children('input').attr('code'), title : $(this).next('li').html(), quantity : $('#p-'+ $(this).prev('li').children('input').attr('lm') ).val(), price : $(this).prev('li').children('input').attr('price'), weight : $(this).prev('li').children('input').attr('weight'), taxable : $(this).prev('li').children('input').attr('taxable'), productId : $(this).prev('li').children('input').attr('productId'), links : $(this).prev('li').children('input').attr('productLinks') }, '#p-'+ $(this).prev('li').children('input').attr('lm'), false, ( parseFloat($(selector).val()) - 1 ) ); return false; }); $('input.product-qty').bind( 'keyup', function(){ Remote.Cart.lastProduct = '#p-'+ $(this).attr('lm'); Remote.Cart.Products.Push( Remote.Cart.customerKey, { code : $(this).attr('code') , title : $(this).parent().next('li').next('li').html(), quantity : $(this).val(), price : $(this).attr('price'), weight : $(this).attr('weight'), taxable : $(this).attr('taxable'), productId : $(this).attr('productId'), links : $(this).attr('productLinks') }, '#p-'+ $(this).attr('lm'), false, previousValue ); }); 

您绑定了一个处理程序2500次,而是使您的函数使用live或delegate,如下所示:

 $('li.product-code').live('click', function(event){ $('input.product-qty').live('keyup', function(){ 

.live()侦听点击在DOM级别冒泡,然后使用点击源的上下文执行事件。 这意味着你有一个事件处理程序而不是2500个,这意味着它在浏览器上更快更容易。

如果你有一个容器来包装未被替换的替换内容(保留在所有AJAX调用中),你可以使它更像是本地的:

 $('#container').delegate('li.product-code', 'click', function(event){ $('#container').delegate('input.product-qty', 'keyup', function(){ 

结果是事件泡沫被捕获的次数减少了。

另一个痛点可能是元素的创建,你可以发布那些代码吗? 通常很容易进行优化,从而在那里产生巨大的性能提升。

更新

从jQuery 1.7开始,不推荐使用.live()方法。 使用.on()附加事件处理程序。 旧版jQuery的用户应该使用.delegate()优先于.live() – JQuery Docs

将您的点击事件绑定到整个文档,在该函数中,查看event.target以查看实际点击了哪个产品元素。 这样你只需要做一次绑定。

你应该看一下jqrid或flexigrid的东西 ,你可以让你做分页,一次分配数据就可以一次输出所以最好限制你一次输出的数量,即使这些东西适合你的项目,你必须弄清楚如何限制数据是底线

首先,使用Firebug中内置的分析器来检查大部分延迟的位置; 只需点击“个人资料”,运行你的慢动作,再次点击它,看看哪个电话最贵。

其次,看看“实时”事件处理: http : //api.jquery.com/live/

它的工作方式是只有一个事件处理程序,查看整个文档,委托给实时事件处理程序。 当您有大量元素时,这会更快地运行,因为您不需要特别为每个元素添加事件处理程序。