tl;dr If you don't need to use e.preventDefault()
in the event, then add passive: true
.
This is my understanding of it.
Every event has its default event handling.
We can use addEventListener
to add event listeners for a specific event. Within this added event, we can use preventDefault()
to avoid executing its default event.
Even if you use preventDefault(), it actually still executes the default event; it just checks whether you have used preventDefault() in its pre-actions. If so, it won't execute. However, checking preventDefault()
in the default event incurs significant overhead.
Therefore, if you can inform passive: true
within addEventListener, it will significantly speed up the process of determining whether to execute the default event. It will be directly treated as false, meaning it will execute the default event.
<script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/8.14.0/mermaid.min.js"></script>
<div class="mermaid">
flowchart TD
A[xxxEvent] --> B[default xxxEvent]
B-->C{check}
C --> |passive:false| E{preventDefault}
E --> |true|return
E --> |false|G[do default event]
C --> |passive:true| G[do default event]
</div>
Therefore, setting passive: true
is a better choice when you don't need to use preventDefault
.
Its default value is not true to ensure compatibility.
If it were set to true, older programs using preventDefault
would essentially be equivalent to not setting it at all.