Tuesday, October 25, 2011

JS getCSSPropertyName Function

I was re-checking @LeaVerou talk at jsconf.eu looking forward to see mine there too to understand how to improve and specially what the hell I have said for 45 minutes :D

Lea made many valid points in her presentation but as is for supports.property case, you never want to go too deep into a single point of your talk so ... here I come.

getCSSPropertyName Function

This function aim is to understand if the current browser supports a generic CSS property. If property is supported, the whole name included prefix will be returned.

var getCSSPropertyName = (function () {
var
prefixes = ["", "-webkit-", "-moz-", "-ms-", "-o-", "-khtml-"],
dummy = document.createElement("_"),
style = dummy.style,
cache = {},
length = prefixes.length,
i = 0,
pre
;
function testThat(name) {
for (i = 0; i < length; ++i) {
pre = prefixes[i] + name;
if (
pre in style || (
(style.cssText = pre + ":inherit") &&
style.getPropertyValue(pre)
)
) return pre;
}
return null;
}
return function getCSSPropertyName(name) {
return cache.hasOwnProperty(name) ?
cache[name] :
cache[name] = testThat(name)
;
};
}());

The function returns a string or null, if no property has been found.

// enable HW acceleration
var cssPropertyName = getCSSPropertyName("transform");
if (cssPropertyName != null) {
node.style.cssText += cssPropertyName + ":translate3d(0,0,0);";
}

Please feel free to test this function and let me know if something went wrong, thanks ;-)

5 comments:

itrelease said...

To prevent looping everytime in testThat you can cache vendor prefix when this function find some property.

Andrea Giammarchi said...

loop has length 6 and I did not think about it but that's a valid point, thanks!

Andrea Giammarchi said...

thinking about it, some property may have -khtml- prefix while some other could have -webkit- one.
Since we generally use a subset of all CSS properties I would say the caching is enough and a loop of 6 prefixes cannot hurt much, considering the function is less "false positive prone" in that way and also simpler to understand. Only thing I should test is getPropertyValue in non W3C browsers since I believe IE7 will fail in that point.

Peter van der Zee said...

How relevant is the -khtml prefix anymore?

Andrea Giammarchi said...

I don't have numbers but it does not hurt much there so some edge case may be covered hopefully without problems.