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