Search code examples
javascriptjqueryjquery-eventsevent-delegation

Event delegation from document or next static parent


Let's say we have the following HTML (with a button added after the page has loaded):

<div id="container">
    <button>Static button</button>
    <button>Dynamical button</button>
</div>

Now I'd like to know the exact difference between these two event handlers:

$(document).on('click', '#container button', function() {});

$('#container').on('click', 'button', function() {});

As far I as I understand the event bubbling, the second example executes the callback function slightly faster. That's because the click event gets fired when the container anchor is reached and in the first example it's fired when the document is reached. I can imagine that in complex structured website that could cause some performance gain.

Am I right with this? Are there any other benefits? And if the performance differences are vanishing can I just attach all events to the document to guarantee that dynamically added elements are handled as well?


Solution

  • Yes, there are performance gains of the second version over the first.

    But not because the event takes less time to bubble. That is totally negligible. Instead, it is about reduced overhead - if you bind the handler to document, then all click events in the entire document need to be tested against your selector #container button every time, not only those that bubbled from inside the container.

    The jQuery docs on Event Performance state this:

    Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.