Setting the style attribute

Benchmark created by David Mark on


Description

Like most browser scripting operations, setting an element’s STYLE attribute may or may not be needed (most apps not). Of course, most libraries attempt to clear that hurdle in one way or another. You get the extra code (and overhead) whether it is beneficial or not. A lot of libraries (as well as old copies of others) use UA-based browser sniffing to “fix” issues with IE5/6/7/compat mode.

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 all tests
  
  var elHtml = document.documentElement;
  var css = 'color:black;background-color:white';
  
  // For My Library test
  
  var setAttribute = API.setAttribute;
  
  // For cross-browser test
  
  // Remove else case to degrade in IE under 8
  // First branch weeds out bad IE browsers (and other older browsers)
  // For completeness, should probably do a try-catch on a set as well
  // Can check that styles take in properties and (in some cases) in layout
  
  if (elHtml) { // Need this for detection, could also create element
    if (elHtml.setAttribute && elHtml.getAttribute && typeof elHtml.getAttribute('style') == 'string') {
      var setStyleAttribute = function(el, css) {
        el.setAttribute('style', css);
      };
    } else if (elHtml.style && typeof elHtml.style.cssText == 'string') {
      var setStyleAttribute = function(el, css) {
        el.style.cssText = css;
      };
    }
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
My Library
setAttribute(elHtml, 'style', css);
ready
jQuery
jQuery(elHtml).attr('style', css);
ready
Cross-browser
// NOTE: Would not normally have API feature detection in loop

if (setStyleAttribute) {
  setStyleAttribute(elHtml, css);
} 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