Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For JavaScript event, is bubble better than capture?

In jQuery, the default time for event handler is bubble time. Is there any advantage over the other?

Isn't capture faster than bubble?

like image 608
Hank Avatar asked Dec 24 '22 11:12

Hank


1 Answers

is bubble better than capture?

No. It's also not worse. Just different.

Isn't capture faster than bubble?

Depends on your definition of "faster". Event listeners added in the capture phase will fire before those in the bubble phase, but all of them will complete before the browser redraws, so there's no real performance benefit to using one or the other.

There are some noteworthy differences though:

Not all events bubble. Events like focus and load do not bubble. This means that if you attach a non-capture event listener to a non-bubbling event on an element, you can be sure that only that element fired the event, and not one of their children. Conversely, you could attach a single event listener using the capture phase, and dynamically get which element fired it, and reduce the number of listeners and respond to future elements.

The capture phase can stop propagating an event before it reaches the children. It's probably more common to cancel an event before it bubbles up to a parent element. However, it can be useful to cancel an event before it reaches a child, in which case the capture phase does have an advantage (or disadvantage).

In conclusions:

Choose the right capture mode for the desired functionality. There is no real performance advantages to either in most cases, and even if there were it would be a micro-optimization.

like image 185
Alexander O'Mara Avatar answered Dec 28 '22 05:12

Alexander O'Mara