jQuery event delegation: bind on document & parent table

JavaScript performance comparison

Revision 62 of this test case created by Raven

Info

Comparing performance of adding .click() to 100 table cells vs using .on() to listen for click events bubbling up the DOM tree.

Preparation code

<style>
td{height:30px;}
.active{
  background-color:red;
}
</style>
<table id="my-table">
  <tr><td>1</td></tr>
</table>
<table id="my-table2">
  <tr><td>2</td></tr>
</table>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var td1 = $('#my-table').find('td'),
        td2 = $('#my-table2').find('td');
   
    $(document).on('click', '#my-table td', function(){
      $(this).toggleClass('active');
    })
   
    $('#my-table2').on('click', 'td', function(){
      $(this).toggleClass('active');
    })
};
</script>

Preparation code output

1
2

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
on document
td1.trigger('click');
pending…
on table
td2.trigger('click');
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment