Performance of jQuery live() event handler
I'm considering usin开发者_StackOverflow社区g 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/
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.
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+
精彩评论