6

I've read the jQuery documentation on event handling, but I still can't really understand what I should do.

I have a mobile app where content is loaded with ajax, so events can't be bound at document onLoad for that content.

As my application grow I now start to be concerned that wrong event handling can give performance problem.

What is the implications on performance choosing between on(), live() and delegate() ?

Something else to take into consideration?

4 Answers 4

6

From jQuery 1.7, the official (and most performant) way to bind events is .on and .off. It's fastest when combined with an id based selector:

$('#id').on('click', myHandler);

.on supercedes .live .delegate and .bind, see here for more info:

http://blog.jquery.com/2011/11/03/jquery-1-7-released/

4

Starting with jQuery 1.7, it is recommended that all new code going forward use on() and off() for all event handling.

http://blog.jquery.com/2011/11/03/jquery-1-7-released/

1

As of jQuery 1.7 the jQuery team/API advise that:

[the] .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

Reference: live() API reference, at: http://api.jquery.com/live/

So the choice, post jQuery 1.7, is between on() and delegate(); and the recommendation, above, seems to suggest that you should use .on() in preference to delegate(). Although I can't argue as to why that is.

2
  • So you don't see any difference between on() and delegate, except that on() is recommend?
    – user920041
    Commented Nov 19, 2011 at 22:45
  • 1
    Honestly, no; except that it feels as if they're tidying up jQuery somewhat, and the idea of .on() and .off() seems to imply that .delegate(), since it seems to do much the same thing as .on(), will likely be deprecated in the future. Commented Nov 19, 2011 at 22:49
1

In case you're creating a javascript application for yourself or for your own product, you should use jQuery 1.7 and .on() method.

In case you're doing some kind of plugin, which can be used on older versions, I would use .delegate()