Tuesday, January 21, 2014

Modernizr - Detecting HTML5 and CSS3 features in client browser easily! <Part 2>


Continuing with the Modernizr series, we now start with the implementation.

So how to go about implementing these compatibility checks?

Until recently, we have been using many techniques for Browser Detection, the most common of which is to use JavaScript for getting information from the user-agent header.

Listing 1 provides us an idea about implementing the user-agent header check (a.k.a. UA sniffing).

   1: <script type="text/javascript">
   2: ieDetectionFunction(){
   3:   if ( navigator.userAgent.indexOf("MSIE") > 0 ) {
   4:     // Yes, we have IE, now do IE related stuff!
   5:   }
   6: }
   7: </script>

Listing 1: Function with user-agent header check

Though UA sniffing has been a standard practice, nevertheless it poses some issues. Considering the above example, we are faced with the inability to ascertain the exact ‘MSIE’ version in this case. Moreover, it also doesn’t provide any function specific checking.

For checking versions, the workaround is to use the navigator object in combination with regular expressions to detect the various browsers and their exact versions.

Specifically, we would query the navigator.appName and navigator.userAgent properties. However, using this approach again won’t solve the feature detection handicap mentioned above.

It would be both faster and more reliable to have the ability of using probing functions which can confirm the availability of objects, methods, attributes and so on (i.e. catering to the 4 points mentioned in the previous section)

We can always create these probing functions which then query for the required stuff, and if not found return null. But the overheads for these custom monitor functions increase if we are having a big web based project, intended to run on multitude browsers.

Enter the JavaScript library, Modernizr.