我在使用多个jQuery绑定数千个元素和输入时遇到加载速度问题,有没有更有效的方法呢?
该站点具有通过ajax调用在产品列表之间切换的能力,页面无法刷新.有些列表有10个项目,大约100个,有些超过2000个.当我开始在列表之间翻转时出现速度问题; 每次加载2000+项目列表时,系统拖动大约10秒钟.
在重建列表之前,我将目标元素的html设置为'',并取消绑定下面的两个绑定.我确定它与我在回调中所做的所有父,子和子调用有关.任何帮助深表感谢.
循环2500次
<ul>
<li><input type="text" class="product-code" /></li>
<li>PROD-CODE</li>
...
<li>PRICE</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
结束循环
$('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
);
});
Run Code Online (Sandbox Code Playgroud)
Nic*_*ver 28
您绑定了一个处理程序2500次,而是使您的函数使用live或delegate,如下所示:
$('li.product-code').live('click', function(event){
$('input.product-qty').live('keyup', function(){
Run Code Online (Sandbox Code Playgroud)
.live()侦听点击以在DOM级别冒泡,然后使用点击源的上下文执行事件.这意味着你有一个事件处理程序,而不是他们的2500,这意味着它是很多更快,更容易在浏览器上.
如果你有一个容器来包装未被替换的替换内容(保留在所有AJAX调用中),你可以使它更像是本地的:
$('#container').delegate('li.product-code', 'click', function(event){
$('#container').delegate('input.product-qty', 'keyup', function(){
Run Code Online (Sandbox Code Playgroud)
结果是事件泡沫被捕获之前的次数减少了.
另一个痛点可能是元素的创建,你可以发布那些代码吗?通常可以通过简单的优化来提高性能.
更新
从jQuery 1.7开始,不推荐使用.live()方法.使用.on()附加事件处理程序.旧版jQuery的用户应该使用.delegate()优先于.live() - JQuery Docs
| 归档时间: |
|
| 查看次数: |
3088 次 |
| 最近记录: |