In jQuery, should I choose live (), delegate () or on ()?

I read the jQuery event handling documentation, but I still can't figure out what I should do.

I have a mobile application where content is loaded using ajax, so events cannot be attached to the onLoad document for this content.

As my application grows, I begin to worry that improper event handling can lead to performance problems.

What are the consequences of choosing a performance between the on (), live (), and delegate () functions?

Anything else to consider?

+6
source share
4 answers

From jQuery 1.7, the official (and most efficient) way to bind events is .on and .off . It is the fastest in combination with the id selector:

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

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

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

+6
source

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

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

+4
source

As in jQuery 1.7, the jQuery / API command reports that:

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

Link: live() API Link: http://api.jquery.com/live/

So the choice, post jQuery 1.7, is between on() and delegate() ; and the above recommendation seems to suggest that you should use .on() , preferring delegate() . Although I can not argue about why this is so.

+1
source

If you are creating a javascript application for yourself or for your own product, you should use jQuery 1.7 and .on() method.

If you are making some kind of plugin that can be used in older versions, I would use .delegate()

+1
source

Source: https://habr.com/ru/post/901903/


All Articles