Search code examples
jqueryperformancejquery-eventsevent-bubblingevent-propagation

Stop event bubbling - increases performance?


If I'm not returning false from an event callback, or using e.stopPropagation feature of jQuery, the event bubbles up the DOM.

In most scenarios I don't care if the event bubbles or not. Like with this DOM structure example:

​<div id="theDiv">
    <form id="theForm" >
        <input type="submit" value="submit"/> 
    </form>
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Normally, I don't have multiple nested submit callback like this:

$('#theDiv').submit(function() {
    alert('DIV!');
});
$('#theForm').submit(function(e) {
    alert('FORM!');
    e.preventDefault();
});​

Fiddle
That DEMO shows the submit event bubbles to a <div>!
It has no difference to me if I stop the Propagation or just prevent default.

In those scenarios, If I stop the propagation will I gain performance benefits?


Solution

  • Performance benefits? Yes, there are some slight benefits, as outlined in this performance test between jQuery live() and on(). As @Joseph also noted, the difference between the two is that live propagates all the way up the tree, while on() only goes to the nearest common parent.

    In those tests, it is shown that on() can outperform live() by up to 4 times. In practice, that's probably still not worth splitting hairs over, but if you have very deep html structures and lots of event triggers, the performance difference in stopping propagation can be worthwhile, I suppose.