jQuery event delegation (v44)

Revision 44 of this benchmark created on


Preparation HTML

<div style="height: 200px; overflow: auto">
  <div id="grandparent">
  </div>
</div>
<script src="https://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>

Setup

$('#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 = []

Test runner

Ready to run.

Testing in
TestOps/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();
}
ready
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();
}
ready
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();
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.