Detects Support for HTML5 and CSS3

There are lots of new and cool features in HTML5 such as canvas, geolocation, etc. Unfortunetely not all browsers support the features. So, how do we detects whether or not a browser supports a particular feature? Here are four basic techniques I extracted from diveintohtml5.org:

1. Check if a certain property exists on a global object (such as window or navigator).


function testGeolocation() {

    return !!navigator.geolocation;

}

2. Create an element, then check if a certain property exists on that element.


function testCanvas() {

    return !!document.createElement('canvas').getContext;

}

3. Create an element, check  if a certain method exists on that element, then call the method and check the value it returns.

function testVideo() { 
 if (!document.createElement('video').canPlayType) {
   return false;
 }
  var v = document.createElement("video");
  return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
}

4. Create an element, set a property to a certain value, then check if the property has retained its value.

   var i = document.createElement("input");
   i.setAttribute("type", "datetime");
   return i.type !== "datetime";

Of course there is the 5th way, which is to use a HTML5 detection library. it is called Modernizr. It is an open source and MIT-licensed.

Modernizr is a small and simple JavaScript library that helps you take advantage of emerging web technologies (CSS3, HTML 5) while still maintaining a fine level of control over older browsers that may not yet support these new technologies.

To use it, simply include the Modernizr script into your page. You can download the script from http://www.modernizr.com/

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="modernizr.min.js"></script>
</head>
<body>
  ...
</body>
</html>

Looking back at the examples from the 4 basic techniques above, here is how it looks like using Modernizr

if (Modernizr.geolocation){
  navigator.geolocation.getCurrentPosition(function(position) {
    setUserLatandLong(position.coords.latitude,position.coords.longitude);
  }); 
} else {
 // Sorry, your browser is very old.
}

There are more example on the documentation site.

Advertisements