My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Tuesday, January 29, 2013

experimental.js

This is a tiny post about a tiny utility, something Modernizr like, but actually much simplified, like about 330 bytes minzipped.
Of course the power is kinda limited, but for most common things such requestAnimationFrame or CSS transition it should be more than enough.

Basic Example

You can find more in the experimental.js repository but here a couple of examples:
// check if present and use it
if (experimental(window, "requestAnimationFrame",
  true // optional third flag to assign the found property
)) {
  // in this case attached directly to the global
  // so we can just use it all over
  requestAnimationFrame(callback);
} else {
  setTimeout(callback, 10);
}
Another example, discovering the right string for transition:
var TRANSITION = experimental(body.style, "transition");
alert(TRANSITION);
// mozTransition
// webkitTransition
// oTransition
// msTransition
// or just transition
If you are wondering about pure CSS, it's easy to add a tiny extra step such:
function toCSSProperty(JS) {
  return JS
    .replace(
      /([a-z])([A-Z])/g,
      function (m, $1, $2) {
        return $1 + "-" + $2;
      }
    )
    .replace(
      /^(?:ms|moz|o|webkit|khtml)/,
      function (m) {
        return "-" + m;
      }
    )
    .toLowerCase()
  ;
}
var CSS_TRANSITION = toCSSProperty(
  TRANSITION
);
As we can see, it's easy to grab new features following the almost de-facto rule about checking properties with prefixes too in objects.
Bear in mind this is not as powerful sa Modernizr, neither it offers any yep/nope mechanism to download on features test library, got it? :)

Online Test

I have created an idiotic page which aim is to test experimental.js against most common objects, here an example.

No comments: