Adding listeners

Benchmark created by David Mark on


Description

Basic DOM operation: adding a listener to an element

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<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>
<script src="//www.cinsoft.net/mylib099-min.js"></script>
<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;
  };
</script>

Test runner

Ready to run.

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

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

Revisions

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