Home > Web Front-end > JS Tutorial > How Does Vanilla JavaScript Event Delegation Improve Performance over Multiple Individual Event Listeners?

How Does Vanilla JavaScript Event Delegation Improve Performance over Multiple Individual Event Listeners?

Mary-Kate Olsen
Release: 2024-11-30 17:48:13
Original
697 people have browsed it

How Does Vanilla JavaScript Event Delegation Improve Performance over Multiple Individual Event Listeners?

Vanilla JavaScript Event Delegation: A Detailed Analysis

Background

Event delegation is a technique used to simplify the handling of multiple event listeners attached to different elements within a DOM structure. In vanilla JavaScript, this can be achieved using .addEventListener().

Event Delegation in Vanilla JS

To translate the jQuery example provided in the question:

$('#main').on('click', '.focused', function() {
    settingsPanel();
});
Copy after login

... into vanilla JavaScript, we would use:

document.querySelector('#main').addEventListener('click', (e) => {
  if (e.target.closest('#main .focused')) {
    settingsPanel();
  }
});
Copy after login

Improved Solution

However, to optimize performance and avoid excessive DOM traversal, it's recommended to pass only the inner selector to .closest():

document.querySelector('#main').addEventListener('click', (e) => {
  if (e.target.closest('.focused')) {
    settingsPanel();
  }
});
Copy after login

Simplifying Code Structure

For readability, it's common to check for the condition within an early return statement:

document.querySelector('#main').addEventListener('click', (e) => {
  if (!e.target.closest('.focused')) {
    return;
  }
  // Remaining code of settingsPanel here
});
Copy after login

Performance Comparison

Compared to the alternative solution provided in the question (document.getElementById('main').addEventListener('click', doThis);), this method offers improved performance, as it employs event bubbling and avoids iterating through numerous child elements within #main.

Live Demo

To illustrate the difference, you can refer to the live demo snippet provided in the answer. Upon clicking the inner element (#inner), both the vanilla JavaScript and jQuery event handlers will log their respective messages to the console.

The above is the detailed content of How Does Vanilla JavaScript Event Delegation Improve Performance over Multiple Individual Event Listeners?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template