Stop event bubbling - increases performance?

对着背影说爱祢 提交于 2020-01-03 12:35:27

问题


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?


回答1:


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.




回答2:


here's a comparison between on() and live() which involve bubbling and the reason jQuery replaced live(). the problem with live() was that events were attached to the document, causing a long travel up the tree to find the handler. what you can do with on() is you can attach the handler to the nearest common parent, thus avoiding the long travel up the tree in search for a handler - which means faster performance.

but i suggest doing your own benchmarks to check.




回答3:


This test shows there is a performance advantage to killing the event early. (15%-30%) And there would probably be a bigger difference on a complex DOM. Its also interesting to note that capturing event listeners seem to be slightly faster than bubbling event listeners regardless of what you do with the event after handling it. Strange but interesting; I only tested in one browser though



来源:https://stackoverflow.com/questions/9730849/stop-event-bubbling-increases-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!