Search code examples
javascriptjquerydomjquery-eventsevent-binding

Event Binding Methods & Performance $(document).on("click", "#id", fn) VS $("#id").on("click", fn)


Which one of following is better in terms of performance etc. and why?

1. `$(document).on("click", "#id", function (e) {   });` 
 
2. `$("#id").on("click", function (e) {   })`
   
3. `$("#id").die('click').live("click",function(e){ });`

4. `$("#id").live("click",function(e){ });`

What will be the effect on performance if we use event delegation? I am looking for an in-depth explanation.


Solution

  • TLTR The explanation of all the above specified methods are given below.

    1. $(document).on("click", "#id", function (e) { });

    This way of binding events, called event delegation, on the the document or a static parent element(say body) rather than to a particular specific element is done in case of dynamic DOM manipulation. A good example is that, think about a situation where you want to bind an event to a DOM element which may not be there when the page is loaded, but will be introduced into the DOM at a later stage by remote loading or by dynamic DOM manipulation. Your code won't be neat if you bind the events for newly introduced elements right after it is introduced in the DOM. So in such cases we use the above method to bind the events initially so that we don't have to worry whether the element is there or not while the binding happens. Here the click event is binded to the document and then delegated to the element specified. Since this is binded to the document or a static parent, the event propagation time will be more, i.e. event propagation will be slow, compared to the second method. But this is the preferred way of doing it.

    1. $("#id").on("click", function (e) { })

    This kind of binding is used in cases where the DOM need not be static, but the element you specify has be present while you bind the event. Usually we do this in static DOM element cases. The only thing is that this kind of binding can be used only when that particular element onto which the event has to be binded is already present in the DOM. Since this is a direct binding and does not involve any delegation event propagation will be fast compared to method 1.

    Since the first kind of binding is done on the document, it will be slow compared to the second one in which event is directly binded onto the specific element.

    1. $("#id").die('click').live("click",function(e){ }); and
    2. $("#id").live("click",function(e){ }); have been deprecated in jQuery 1.7 and removed in jQuery 1.9.

    "Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled." - Quoted from https://api.jquery.com/live/.

    This is answer for your question, which method is faster?

    Method 2 > Method 1 > Method 3 & 4
    

    But still Method 1 is the preferred method.