大型列表上单击事件的 jQuery 委托性能 - 如果动态添加更多元素,速度会变慢?
我有一个这样的项目的可视列表:
http://jsfiddle.net/viatropos/XCe3T/1/
在真实的应用程序中,我总共只加载 200 个项目。但问题是,即使只有 200 个项目,click
事件也需要几乎一秒钟的时间来调用处理程序。无论列表中有多少项,mouseover
事件回调都会立即执行。
我的问题是,无论页面上有多少元素,委托方法不应该一样快吗?我所做的就是这样:
$("body").delegate("a", "click", function(event) { console.log($(event.target).get(0)); return false; }
如果您转到上面的 jsfiddle 示例和 Web 检查器,然后单击渲染结果中的链接,它将添加 200 个以上元素。请注意添加的元素越多,速度就越慢。奇怪的是,如果你从 6000 个项目开始,委托/单击的执行速度比从 2000 个项目开始并一次添加 200 个直到达到 6000 快得多。
你的想法是什么,我如何提高 jQuery 的性能click
事件的 delegate
方法? css 是否会导致速度变慢(可能样式太多或布局未优化)?
I have a visual list of items like this:
http://jsfiddle.net/viatropos/XCe3T/1/
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; }
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.
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据我的经验,重新初始化(取消绑定然后再次绑定事件处理程序)比使用 .live 或 .delegate 更好(性能方面)。
这样您就应该获得所需的性能。
实际上,我会定义一个委托变慢的阈值,删除所有绑定并将事件处理程序重新绑定到现有的元素集。
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.