简体   繁体   中英

JS/jQuery - Better to run event handler in $(document).ready or in called function

*Note: The following question is not meant to be for people's opinion but is being asked in terms of best processing speed for the webpage, jQuery, etc.

I currently have code which follows the below "test" code format:

$(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 (not the event listener) be in the same code structure as $(document).ready(); ? Or should it 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);
  }
});

ie should $(document).ready(); only have the listeners which reference the handlers or should the entire action (of listening and handling) be in $(document).ready();

What is the proper way of doing this so as to maximize the usability/power of jQuery, JS, etc.

I would go with the first snippet of code:

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

You are not doing anything with the function toggler before the DOM is ready, so why define it outside.

I'm sorry about giving a general and obvious answer : To be sure, only one way, doing benchmark. Using PHP for generating 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 your other javascript implementation, then run them. Look how long the page/DOM takes to load, and how long it takes to manage the click event (using your browser toolkit). Increase the number of genereted elements if you can't notice any difference between the two version.

Going this way will help you to solve every optimization problem you could meet ("honest" benchmark are somtimes tricky to make).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM