Event Attach on Load

JavaScript performance comparison

Test case created by Phillip Gourley

Info

Which is better - adding 100's of events in jQuery or adding them to markup without any any additional binding?

Spike for better management of GA tracking events.

Preparation code

<div id="dump">

</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var $dump = $('#dump');
   
    function tracker() {
   
      // Cleanup
      $dump.html('');
    }
};
</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
Attach event after DOM load
for (var i = 0, len = 10; i < len; ++i) {
  $dump.append('<a href="#" class="link">Text</a>');
};

var $linkDump = $('.link');

$linkDump.click(function() {
  var $this = $(this),
    action = "Click",
    category = "Test",
    label = $this.text();
 
  console.log(action, category, label);

  // Cleanup
  $dump.html('');
});

$linkDump.click();
pending…
Attach with DOM
for (var i = 0, len = 10; i < len; ++i) {
  $dump.append('<a href="#" class="link" onclick="tracker()">Text</a>');
};

var $linkDump = $('.link');

$linkDump.click();
pending…

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

Compare results of other browsers

0 comments

Add a comment