Detecting HTML5 Feature Availability with Modernizr

Tuesday, November 23, 2010

Unless you’ve been living in a cave for the past several months, you know the about the major shift in web development called HTML5.  It seems everyone is talking about and justly so.  It was the number one top trends for 2010 and will continue to change how we write web applications.  Although the spec has not been finalized (indeed, its quite some time away from that), most mainstream browsers have already adopted some elements of HTML5 into their standard releases.

One common misconception is that HTML5 is just one big ‘thing’.  On the contrary, HTML5 is really a bunch of different features which are being defined by the HTML5 spec.  Unfortunately, most browsers do not support all of the features.  This makes it very important that you degrade gracefully when a feature is not supported by the browser.  It’s a small price to pay if you want to be on the bleeding-edge of web technology.  This is especially true if you’re a mobile web developer.

There are several techniques you can script to test for elements, properties of those elements, whether a property retains its value etc.  Instead of incorporating all these checks into your scripts, I would recommend taking a look at Modernizr.

Modernizr is an open source initiative to ease the pain of detecting HTML5 support on your pages.  So, what would commonly take several lines of code to check if the canvas element is supported and provides text functionality can be shrunk to only 1 line with Modernizr.
Without Modernizr:

function supports_canvas_text() {
   if (!supports_canvas()) {
      return false;
   }
   var hidden_canvas = document.createElement('canvas');
   var ctx = hidden_canvas.getContext('2d');
   return typeof ctx.fillText == 'function';
}

and with Modernizr:

if (Modernizr.canvastext)  {
   //supported
}

Eventually all browsers will support the full HTML5 spec and these checks will become unnecessary. But in the meantime, if you’re inclined to start leveraging HTML5, Modernizr is a must-have for your scripting toolset.

Leave a Reply