livequery performance
Asked Answered
B

1

11

I've recently discovered that livequery plugin for jQuery may be quite wasteful, as it does not use event delegation but binds all bindable events and re-checks the whole DOM on each change

if anyone has more information or suggestions on best practices using livequery and .live(), I would be very grateful

Bigamist answered 27/1, 2011 at 15:5 Comment(1)
As noted in the answer by "patrick dw" below, the .live() and .delegate() pretty much are integration by the same author of livequery into the core - see his blog here: brandonaaron.net/blog at least as I understand it :)Garett
G
11

It is rare that you would actually need a plugin like livequery. Probably the only time you really need it is if you need to react to changes to the DOM made by some other jQuery code that you can not modify.

While .live() does use event delegation, it does it on the document level, which means that it needs to process all events on the page to see if they match the selectors provided per event type.

A better alternative (IMO) to both of those is the delegate()(docs) method which uses event delegation just like .live(), but lets you constrain it to a specific portion of the page.

$('#someContainer').delegate('a.someButton', 'click', function() {
    // do something when an "a.someButton" inside "#someContainer" is clicked
});

Note that event delegation methods respond to browser events, not to changes to the DOM. If you need to run some code based on a change to the DOM you've made, you need to run that code when you make that alteration to the DOM.

Granulite answered 27/1, 2011 at 15:11 Comment(1)
This is a great answer, but keep in mind that this approach will only work for events that bubble up. Some events, such as 'invalid' (fired when a form element fails validation) do not bubble up, and thus cannot be captured via delegation.Affer

© 2022 - 2024 — McMap. All rights reserved.