1

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/

Kevin Burke
  • 61,194
  • 76
  • 188
  • 305

2 Answers2

6

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • So the idea is, if I click on an element without a `click` handler, the event bubbles up the DOM until jQuery can find a `click` event handler? – Kevin Burke Jun 17 '11 at 17:04
  • @Kevin Not quite. All events bubble up the DOM tree and trigger all matching event handlers along the way. I.e. if each `div` in `` has an `onclick` handler, all will get executed in order when clicking the link. That's standard DOM behavior, not jQuery. `.live()` just "waits" at the topmost element to receive all `click` events. When it does, it checks whether the element that was originally clicked on matches your selector and calls your event handler function if so. – deceze Jun 18 '11 at 03:36
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+

kapa
  • 77,694
  • 21
  • 158
  • 175
  • You can attach `.live()` to a specific *context* instead of the root element if you want. – deceze Jun 17 '11 at 07:50
  • 1
    @deceze how would you do that, and, more to the point, why? The ".delegate()" interface is usually smarter to use than ".live()", primarily because the initial jQuery object need not be built. (*edit* oh I see, if you build the jQuery object with a context, then it uses that. Still, it needlessly traverses at least part of the DOM to build an element list that usually is not used.) – Pointy Jun 17 '11 at 07:55
  • 1
    Quoting the docs: `$(".clickme", $("#container")[0]).live(...)`. I'm not saying `.delegate` is bad, just that you *can* optimize `.live` a bit. – deceze Jun 17 '11 at 07:57