jQuery对大型列表上的点击事件的委托表现 - 如果您动态添加更多元素,则会降低速度? [英] jQuery delegate performance on the click event on large lists - slows down if you dynamically add more elements?

查看:138
本文介绍了jQuery对大型列表上的点击事件的委托表现 - 如果您动态添加更多元素,则会降低速度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的项目的视觉列表:

I have a visual list of items like this:

http://jsfiddle.net/viatropos/XCe3T/1/

在真实的应用程序中,我只加载200个总项目。但问题是单击事件花费近一秒钟来调用处理程序,即使只有200个项目。 mouseover 事件回调立即执行,无论列表中有多少项目。

In the real app, I'm only loading 200 total items. But the problem is the click event takes almost one second to call the handler, even with just 200 items. The mouseover event callback executes immediately no matter how many items are in the list.

我的问题是,无论页面上有多少元素,代理方法也是一样快?我所做的就是这样:

My question is, shouldn't the delegate method be just as fast no matter how many elements are on the page? All I am doing is this:

$("body").delegate("a", "click", function(event) { console.log($(event.target).get(0)); return false; }

如果你去上面的jsfiddle示例和Web检查器,并点击渲染结果中的一个链接,它将添加200个元素。注意添加的元素越多越慢,奇怪的是如果您开始使用6000个项目,那么委托/点击执行的速度要比2000年开始的速度要快很多,直到达到6000。

If you go to that jsfiddle example above and the web inspector, and click a link in the rendered result, it'll add 200 more elements. Notice how the more elements you add, the slower it gets. The weird thing is, if you start with 6000 items, delegate/click executes a lot faster than if you start with 2000 and add 200 at a time until you get to 6000.

你的想法,如何提高jQuery的委托方法对于点击事件的性能?css可能导致这个减少(可能太多样式或未优化的布局)?

What are your thoughts, how do I improve the performance of jQuery's delegate method for the click event? Could the css be causing this to slow down (maybe too many styles or an unoptimized layout)?

推荐答案

根据我的经验,更好(性能明智)重新初始化(解除绑定,然后再绑定事件处理程序)比使用.live或.delegate。
那你应该实现你所需要的表现。
实际上,我将定义一个阈值,代理变得缓慢,删除所有的绑定,并将eventHandler重新绑定到现有的元素集。

Based on my experience it is better (performance wise) to reinitialize (unbind and then bind event handlers again) than to use .live or .delegate. That way you should achieve the performance you need. Practically I would define a threshhold where delegate becomes slow, remove all the bindings and rebind the eventHandlers to the existing set of elements.

这篇关于jQuery对大型列表上的点击事件的委托表现 - 如果您动态添加更多元素,则会降低速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆