Too many handlers hung on elements eat up a lot of RAM and lead to page freezes.
Let's look at an example. Let's have some list:
<ul></ul>
We get a reference to this list into a variable:
let ul = document.querySelector('ul');
Now let's fill our list with li
tags, attaching a click handler to them:
for (let i = 1; i <= 1000; i++) {
let li = document.createElement('li');
li.textContent = i;
ul.append(li);
li.addEventListener('click', function() {
console.log(this.textContent);
});
}
As a result, it turns out that we have
1000
handlers. This is a lot. For
optimization, we can attach only one
handler to the ul
tag using a
delegation.
Let's do that. First, let's just create the list items:
for (let i = 1; i <= 1000; i++) {
let li = document.createElement('li');
li.textContent = i;
ul.append(li);
}
Now let's use delegation of the event handler:
ul.addEventListener('click', function(event) {
let li = event.target.closest('li');
if (li) {
console.log(li.textContent);
}
});
Create an HTML table of size
100
by 100
. Make
each cell turn red on click.