Perfection Kills

by kangax

Exploring Javascript by example

← back 1062 words

Feature testing CSS properties

Contrary to many beliefs, detecting CSS properties support with Javascript is not very complicated. One of the CSS-related tests in Common Feature Tests suite is IS_CSS_BORDER_RADIUS_SUPPORTED which looks as simple as this:


var IS_CSS_BORDER_RADIUS_SUPPORTED = (function() {
  var docEl = document.documentElement, s;
  if (docEl && (s = docEl.style)) {
      return typeof s.borderRadius == "string"
        || typeof s.MozBorderRadius == "string"
        || typeof s.WebkitBorderRadius == "string"
        || typeof s.KhtmlBorderRadius == "string";
  }
  return null;
})();

As you can see, testing a CSS property boils down to an inference drawn from the presence of the same named property in a style of an arbitrary element. If you wanted to test support for a “marginLeft” property, you would do it like so:


var el = document.createElement('div');
typeof el.style.marginLeft == 'string'; // true
typeof el.style.marginLeft2 == 'string'; // false

An alternative (and less verbose) way involves replacing typeof operator with in operator:


var el = document.createElement('div');
'marginLeft' in el.style; // true
'marginLeft2' in el.style; // false

in was actually used in earlier versions of CFT but I find such inference too weak. in doesn’t check type of a property; it merely determines property existence, and would return true even if it had undefined (or any other, non-string) value.

IS_CSS_BORDER_RADIUS_SUPPORTED doesn’t just test CSS3 “borderRadius” property. It also tries some of the known proprietary, vendor-specific variations – “MozBorderRadius”, “WebkitBorderRadius” and “KhtmlBorderRadius”. While tweaking this test a couple of days ago, I realized that if I wanted to test CSS3 “boxShadow” property, I would need to follow the same logic and “iterate” over the very same prefixes – “MozBoxShadow”, “WebkitBoxShadow” and so on. Such duplication was clearly not the way to go and a more generic function seemed like a better solution.

getStyleProperty

What it all led to was a very simple getStyleProperty helper:


var getStyleProperty = (function(){

  var prefixes = ['Moz', 'Webkit', 'Khtml', 'O', 'Ms'];

  function getStyleProperty(propName, element) {
    element = element || document.documentElement;
    var style = element.style,
        prefixed;

    // test standard property first
    if (typeof style[propName] == 'string') return propName;

    // capitalize
    propName = propName.charAt(0).toUpperCase() + propName.slice(1);

    // test vendor specific properties
    for (var i=0, l=prefixes.length; i<l; i++) {
      prefixed = prefixes[i] + propName;
      if (typeof style[prefixed] == 'string') return prefixed;
    }
  }

  return getStyleProperty;
})();

getStyleProperty follows the same logic and returns a first found CSS property on an arbitrary (or optionally specified) element. If you run getStyleProperty('borderRadius') in Mozilla-based browser, it would return “MozBorderRadius”; if it was a Webkit-based client, a “WebkitBorderRadius” would be returned. Finally, if no property was found, methods would exit with undefined.

Simple as that.

The way you would test a property is by comparing returned result’s type to “string”:


if (typeof getStyleProperty('borderRadius') == 'string') {
  // property is supported
}

I didn’t want to recreate a prefixes array every time function is called and stored it in a closure. I also used function declaration inside that closure, rather than returning an anonymous function expression, so that getStyleProperty had a descriptive identifier. There’s a document.documentElement used as a generic element (in case none is provided as a second argument), but I could as well have created a new one with document.createElement.

You’re obviously free to improvise with these subtleties as you find appropriate, as long as the actual testing mechanism is left intact.

Performance considerations

I don’t consider execution speed very crucial for a method such asgetStyleProperty, since it would most likely be executed once or twice and probably during the load time. Nevertheless, two basic optimizations come to mind.

Caching a property is one of them. We can simply create a “private” object that maps original (passed into function) property to an actual (possibly prefixed) one and use that object as a cache:


var getStyleProperty = (function(){

  var prefixes = ['Moz', 'Webkit', 'Khtml', 'O', 'Ms'];
  var _cache = { };

  function getStyleProperty(propName, element) {
    element = element || document.documentElement;
    var style = element.style,
        prefixed,
        uPropName;

    // check cache only when no element is given
    if (arguments.length == 1 && typeof _cache[propName] == 'string') {
      return _cache[propName];
    }
    // test standard property first
    if (typeof style[propName] == 'string') {
      return (_cache[propName] = propName);
    }

    // capitalize
    uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);

    // test vendor specific properties
    for (var i=0, l=prefixes.length; i<l; i++) {
      prefixed = prefixes[i] + uPropName;
      if (typeof style[prefixed] == 'string') {
        return (_cache[propName] = prefixed);
      }
    }
  }

  return getStyleProperty;
})();

Another optimization is to cache vendor prefix, such as “Moz” or “Webkit” rather than a specific property. An assumption we’re making here is that if one prefixed property is found in an element’s style, than that prefix can safely be prepended to any other property resulting in a “proper” string. I’m not sure if such inference is a good thing, since clients are obviously not limited to implementing only one type of vendor-specific properties; I can imagine Khtml-based clients implementing both – Khtml- and Webkit- properties.

It might be safer to just stick to “regular” caching mechanism (if any at all), as in the previous snippet.

Inference downsides

Theoretically speaking, the inference we are relying on for getStyleProperty is not all that strong. A mere existence of a CSS property doesn’t tell us about an actual implementation and its conformance to a specification. A browser might have “borderRadius” property with a proper string value; it could allow to assign to that property and even set its value to a specified one after assignment; yet, it could never make borders rounded. The problem is that many CSS3 declarations affect document in such way that it is impossible to detect their effect on a DOM. Border’s radius and box’s shadow, text’s stroke and text overflow (ending with an ellipsis) are all purely visual aspects. If “marginLeft” conformance can be checked by testing element’s offset (as it is represented in a DOM), most of the CSS3 properties don’t provide such luxury.

This is an important thing to remember.

CFT

getStyleProperty is now part of CFT suite (source of which you can find on github). There’s also a simple test page with some of the common CSS3 properties tested.

As always, I’d love to hear any suggestions/corrections you have.

Did you like this? Donations are welcome

comments powered by Disqus