Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance impact in using live instead of bind in jQuery?

Tags:

jquery

I found some questions regarding the live and bind, but none of them was regarding the performance. I think the title is quite clear, so is there a performance impact in using live in jQuery? Why I'm asking this is beacuse you have to do the lookup everytime the event is fired when using live and my thought is that this might impact the performance in a negative way. Or are jQuery doing some magic stuff that speed up this, like listening to some kind of event that is fired when something is added to the DOM?

like image 707
Tomas Jansson Avatar asked Oct 13 '22 17:10

Tomas Jansson


1 Answers

In general, it has a better overall performance to use .live() / .delegate() when you have lots of (...) elements on your site which need to have an event handler.

It's more expensive to bind 50x event handlers to 50 different nodes than just to bind one event handler to a common parent of these 50 elements (which basically is, what .live() does).

Now one could argue, "well, great, but this comes with overhead event bubbling", which is absolutely correct. That's why .delegate() was introduced. .live() always binds a handler to the document.body which obviously is the parent of any childnode in your markup. .delegate() however takes an argument, where you can specify the "lowest common denominator", which means the closest parentnode that is shared by those elements you want to have an event handler. This reduces the overhead actually to zero.

I have to admit that I never benchmarked (yet) at which point it makes sense to use a "live binding". But then again, it makes sense as soon as you got more than one element to bind handlers to. Only the fact that there only is ONE function instead of N seems convenient to me.

like image 109
jAndy Avatar answered Oct 18 '22 02:10

jAndy