Performance of jQuery live() event handler

三世轮回 提交于 2019-12-24 11:28:01

问题


I'm considering using live() to bind an event handler to a function I haven't inserted into the DOM. However this looks expensive - it must have to do a runtime check any time an element is inserted, or any time a "click" element is performed, for example, to see whether the handler should be called.

Is this something worth worrying about in practice, or is Javascript so fast now that this isn't worth caring about?

Reference page for the live() function: http://api.jquery.com/live/


回答1:


No, .live() uses event bubbling to do its thing. It just attaches to the root element and reacts to events bubbling up through the DOM tree. It does not keep checking DOM elements all the time.

From the very page you link to:

The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to .live() is never bound to an element; instead, .live() binds a special handler to the root of the DOM tree.

Keeping reading there as it goes into more detail.




回答2:


You might be better off using delegate(), which does not attach the handler on the document, but on a parent element specified. This means much less load. It is advised to use it instead of .live() in most situations.

About the differences on Nettuts+



来源:https://stackoverflow.com/questions/6382782/performance-of-jquery-live-event-handler

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