jQuery event delegation

JavaScript performance comparison

Revision 44 of this test case created

Preparation code

<div style="height: 200px; overflow: auto">
  <div id="grandparent">
  </div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<style type="text/css">
  div.active1 { color: red; }
  div.active2 { color: green; }
  div.active3 { color: blue; }
</style>
<script>
Benchmark.prototype.setup = function() {
    $('#grandparent').html('<div id="parent"></div>')
    var $el = $('#parent');
   
    function getHtml(i) {
      return '<div class="clickable" id="' + i + '">Some text<span>more text</span></div>'
    }
   
    var count = 20
    var setup = false;
    var $targets = []
};
</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
for (var i = 0; i < count; i++) {
  $el.append(getHtml(i))
  $targets[i] = $(document.getElementById(i));
  $targets[i].on('click', function() {
    $(this).toggleClass('active1');
  });
}
for (var i = 0; i < count; i++) {
  $targets[i].click();
}
pending…
with delegation
for (var i = 0; i < count; i++) {
  $el.append(getHtml(i))
  $targets[i] = $(document.getElementById(i));
}
if (!setup) {
  $el.on('click', '.clickable', function() {
    $(this).toggleClass('active2');
  });
  setup = true;
}

for (var i = 0; i < count; i++) {
  $targets[i].click();
}
pending…
native delegation
for (var i = 0; i < count; i++) {
  $el.append(getHtml(i))
  $targets[i] = $(document.getElementById(i));
}

if (!setup) {
  $el[0].onclick = function(event) {
    var e = event || window.event,
        target = (typeof e.target != 'undefined') ? e.target : e.srcElement;
    if (target.nodeName == "DIV") {
      $(target).toggleClass('active3');
    }
  }
  setup = true;
}

for (var i = 0; i < count; i++) {
  $targets[i].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