Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 801
gdoron is supporting Monica Avatar asked Mar 16 '12 02:03

gdoron is supporting Monica


People also ask

Why is event bubbling important?

Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element or document object (Provided the handler is initialized).

What is event bubbling capturing how would you use it?

With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. With capturing, the event is first captured by the outermost element and propagated to the inner elements.

What is the difference between stopPropagation and preventDefault?

preventDefault() will not allow the user to leave the page and open the URL. The event. stopPropagation() method stops the propagation of an event from occurring in the bubbling or capturing phase.


1 Answers

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.

like image 65
Herman Schaaf Avatar answered Sep 25 '22 03:09

Herman Schaaf