Javascript performance? - Put events in html tag or link them?

I am wondering what is best for performance ... I have a "web application". It has a lot of javascript. When a button is clicked, the hidden div becomes visible. This new div has 5 buttons. Which is better for performance:

1.) put button click events in the html tag of each button, for example onClick = "alert ('hey'); 2.) Attach events to each button when the div is visible, and then remove the events when I hide the div containing the buttons ?

The reason I'm asking is because I assume the page can get bogged down if events in the html tags are constantly present. I believe that the page can be faster, to have only those events, when the user can see the buttons to click them.

Any help is great! Thanks!

+3
source share
3 answers

I would use event delegation .

Thus, you can freely add / remove any buttons without worrying about adding events to each of them. This approach is also more memory efficient, since each button always has one event handler instead of N.

+2
source

- (, , Google ), JS HTML. . .

+1

, , , .

HTML DOM , . , , . , , (.. ), . , :

<button onclick="if ('red'==this.parent.style.backgroundColor) {...}">...</button>

:

<button onclick="clickColorButton(event)">...</button>
+1

Source: https://habr.com/ru/post/1719062/


All Articles