Adding listeners

Benchmark created by David Mark on


Basic DOM operation: adding a listener to an element

Preparation HTML

<script src="//"></script>
 * Context here is an HTML5 document
 * Appropriate build for this context would exclude XHTML support
 * Next line asserts document will create an HTML DOM
 * There are virtually no documents on the Web that create an XHTML DOM
var API = { disableXmlParseMode:true };
<script src="//"></script>
  // For My Library test
  var attachListener = API.attachListener;
  // For cross-browser test
  // NOTE: Should use isHostMethod for host method detection
  // Degrades below IE 9. Add attachEvent branch to support legacy versions.
  // Could even be done in a script inside conditional comments. ;)
  if (document.documentElement && document.documentElement.addEventListener) {
    var attachEventListener = function(el, eventType, fn) {
      el.addEventListener(eventType, fn, false);
  // For all tests
  var el1 = document.createElement('div');
  var el2 = document.createElement('div');
  var el3 = document.createElement('div');
  var el4 = document.createElement('div');
  var listenerFunction = function() {
    var x = 1;

Test runner

Ready to run.

Testing in
My Library
attachListener(el1, 'click', listenerFunction);
My Library (OO)
E(el2).on('click', listenerFunction);
jQuery(el3).bind('click', listenerFunction);

// NOTE: less concise and no argument to set "this" object :(
if (attachEventListener) { // Conditionally defined
  attachEventListener(el4, 'click', listenerFunction);
} else {
  throw new Error('Abort due to degraded browser');


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

  • Revision 1: published by David Mark on