jQuery event delegation

JavaScript performance comparison

Revision 35 of this test case created by Aaron Forsander

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

<div id="parent"></div>
<div id="parent2"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    $('#parent2').on('click', '.clickable', function() {
      $(this).toggleClass('active');
    });
};

Benchmark.prototype.teardown = function() {
    $('.clickable').remove();
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
no delegation
var $target = $("<div class='clickable'></div>").appendTo('#parent');
$('#parent').on('click', '.clickable', function() {
  $(this).toggleClass('active');
});
$target.click();
pending…
with delegation
var $target = $("<div class='clickable'></div>").appendTo('#parent2');
$target.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