JS / jQuery - it is better to run the event handler in $ (document) .ready or in the called function

* Note. The following question is not intended for people, but is asked in terms of the best processing speed for a web page, jQuery, etc.

I currently have code that follows the following "test" code:

$(document).ready(function() { $('.my-class').on('click') { if ($('.my-class').hasClass('active') { $('.my-class').removeClass('active'); return; } $('.my-class').addClass('active'); } }); 

My question is: should the event handler (and not the event listener) be in the same code structure as $(document).ready(); ? Or it should look like this:

 function toggler(obj) { if ($(obj).hasClass('active') { $(obj).removeClass('active'); return; } $(obj).addClass('active'); } $(document).ready(function() { $('.my-class').on('click') { toggler(this); } }); 

i.e. should $(document).ready(); have only listeners that reference handlers, or all actions (listening and processing) are in $(document).ready();

What is the right way to do this to maximize usability / jQuery, JS, etc.

+6
source share
2 answers

I would go with the first piece of code:

 $(document).ready(function() { $('.my-class').on('click') { if ($('.my-class').hasClass('active') { $('.my-class').removeClass('active'); return; } $('.my-class').addClass('active'); } }); 

You don't do anything with function toggler before the DOM is ready, so why define it outside.

+1
source

I apologize for the general and obvious answer: Of course, there is only one way that performs the benchmark. Using PHP to create 100 elements, we could do:

 <html><head> ... </head><body> <?php for ($i=0;$i<100;$i++){ echo '<div class="my-class">Test</div>'; } ?> <script> function toggler(obj) { if ($(obj).hasClass('active') { $(obj).removeClass('active'); return; } $(obj).addClass('active'); } $(document).ready(function() { $('.my-class').on('click') { toggler(this); } }); </script> </body></html> 

Create another php file with a different javascript implementation, then run them. See how long the / DOM page takes and how long it takes to manage the click event (using your browser toolkit). Increase the number of generated elements if you do not notice the difference between the two versions.

By doing so, you can solve any optimization problem that you might encounter (an β€œhonest” benchmark can sometimes be difficult).

-one
source

All Articles