Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between jQuery live() and liveQuery plugin?

The question says it all. Which one is better and when to use what, I never use jQuery live() as I am using liveQuery plugin for a couple of years, I am used to it and still continue using it. But I want to know the subtle differences between the two and when to use each of it?

like image 254
Teja Kantamneni Avatar asked Feb 04 '10 19:02

Teja Kantamneni


2 Answers

The "live" function native to jQuery leverages the bubbling of events up the DOM. The "liveQuery" plugin, by contrast, uses the selector to find elements in the DOM and attach event handlers directly.

In my opinion you're way better off using the "live" function when possible, because it involves less DOM traversal etc. For example, hooking event handlers to things throughout a big table can be kind-of slow with liveQuery but not slow at all with "live". There may be some issues (with IE of course) that force you to use liveQuery sometimes, though jQuery 1.4 has improved "live" considerably.

editUpdate: Sep 2017

At this point, modern versions of jQuery centralize event handler registration in the .on() API. Briefly:

$(selector).live("event-name", handler);

would today be written with .on():

$(document).on("event-name", selector, handler);

The .on() API provides considerably more flexibility than the long-deprecated .live() method did, including the option of using any node in the DOM as the delegation point (like the old .delegate() did).

like image 142
Pointy Avatar answered Oct 16 '22 05:10

Pointy


As Pointy said, live() leverages the bubbling of events up the DOM (event delegation). Also, for each $(selector).live(type, handler) call, jQuery only calls handler on the $(event.target).closest(selector) element - that is, the nearest matching ancestor-or-self element of the event target. And, of course, live() doesn't support anything like livequery( matchedFn, unmatchedFn ).

Implications:

  • $(selector).live() still requires a traversal of the DOM (obviously). However, if you load jQuery and attach live() handlers in the document head then there is no document body to search yet. Similarly if you insert new content into the page.
  • live() does less work when being configured - it doesn't have to attach handlers to every matched element
  • live() does more work in handling events - it has to traverse ancestors of the event target, finding elements that match the selector
  • $("div").live() is different to $("div").livequery() as it only works for the closest div to the event target
  • Similarly, $("div, p").live() is different to $("div").live(); $("p").live();
like image 37
Sean Hogan Avatar answered Oct 16 '22 05:10

Sean Hogan