Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript performance ? - Put events in html tag, or bind them?

I'm wondering which is better for performance... I have a "web app" sort of thing. It has a lot of javascript. When a button is clicked, a hidden div becomes visible. This new div has 5 buttons. Which is better for performance:

1.) put the button click events in the html tag of each button like 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 ask is because I imagine the page might get bogged down if the events in the html tags are constantly there. I figure the page might be faster to only have those events when the user can see the buttons to click them.

Any help is great! Thanks!


2 Answers

I would use event delegation.

This way you can freely add/remove any buttons without worrying about attaching events on each one of them. This approach is also more memory efficient, since you always have one single event handler instead of N ones directly on each button.

like image 86
kangax Avatar answered Apr 15 '26 15:04

kangax


Unless those events are causing something to act as a link (which it seems Google learned to read) the put all this JS outside your HTML. It makes your code tidier and more maintainable. Can't be sure about performance.

like image 27
Itay Moav -Malimovka Avatar answered Apr 15 '26 17:04

Itay Moav -Malimovka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!