jQuery delegate performance on the click event on large lists - slows down if you dynamically add more elements?

老子叫甜甜 提交于 2019-12-31 02:49:10

问题


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)?


回答1:


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.



来源:https://stackoverflow.com/questions/6576853/jquery-delegate-performance-on-the-click-event-on-large-lists-slows-down-if-yo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!