Search code examples
javascriptjqueryperformance

Is there a performance benefit to using JavaScript's event delegation rather than jQuery's?


JavaScript:

parent.addEventListener("click", function(e) {
  if (e.target === child) { code }
});

vs.

jQuery:

$(parent).on("click", child, function() {});


Solution

  • Marginal, jQuery's on method does a bit more work to give you extra functionality, like running a selector as the event bubbles up to the root, so the event comes from the element you're expecting; if you're not careful, that could be problematic. Citing the documentation, under Event Performance:

    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.

    Plain javascript on the other hand does something more straightforward, just raises any event that happened under that element, so you have to be very specific.

    Having said that, the performance difference is negligible for modern engines under normal circumstances, like a few hundred event handlers.

    However, as @Patrick points out, it could be disastrous for some special cases where you have thousands of elements you need to keep track of and get events from; running selectors in this case, for each event, will kill your performance. Sometimes you will benefit from using special techniques, like only attaching one event handler to the container of said elements and using e.target to find out what actually caused the event.