Automatic growing number of JS event listeners

Viewed 35

I noticed in the Performance tab of Chrome Dev Tools an always increasing number of JS event listeners in my page.

My page is in vanilla JS, and I didn't do anything for that behavior to happen.

What can be causing it?

enter image description here

1 Answers

In order to find the elements that get increasingly many event listeners, you could do the following in your dev console:

const findAllChildren = (e, ee = []) => {
    const children = [...e.children];
    ee.push(...children);
    children.forEach((c) => findAllChildren(c, ee));
    return ee;
};
const allElements = [window, ...findAllChildren(document.body)];
const mapToEntry = (e) => [e, Object.values(getEventListeners(e)).flat().length];

const prev = allElements.map(mapToEntry);

This will collect all counts of event listeners on the different elements.

Then, when you see the event listeners increased run this script afterwards:

const next = allElements.map(mapToEntry);

const increased = prev.map(([e, count], i) => [e, count, next[i][1]]).filter(([_, prevCount, nextCount], i) => prevCount < nextCount);

console.table(increased.map(([element, prevCount, nextCount]) => ({ element, prevCount, nextCount })));

This will print you a table of all elements that got more event listeners attached.

(Chrome) Once, you found the elements, you can inspect in your dev tools pretty easily after clicking in the element inspector on the element and then going to the "Event Listeners" section (sibling of "Styles").

Related