OdeToCode IC Logo


Thursday, October 6, 2011

modernizrModernizr.js is a little library that will help "modernize" old browsers.

As an example, let's say you create a new ASP.NET MVC 3 application with the "Use HTML 5 semantic markup" checkbox selected. If you peek into the layout view for the app, you'll find the following markup:

    <ul id="menu">
        <li>@Html.ActionLink("Home", "Index", "Home")</li>
        <li>@Html.ActionLink("About", "About", "Home")</li>

The nav element represents a section with navigation links, and is a new element in the HTML 5 spec. The idea is that using nav gives more meaning to the page, and allows user agents like screen readers to identify navigation information (contrast nav against using a regular div element as the container  - a div carries relatively no semantic value by itself).

There is a problem, however. Older versions of Internet Explorer (anything before version 9) do not recognize the nav element. IE refuses to apply style rules to unidentified elements, and will also not allow unidentified elements to have children in the DOM. If you have to support older versions of IE this will sound like a dire situation, but it turns out there is an easy solution.

HTML5 Shiv

You can "register" elements in IE using document.createElement. For example…


... is all you need to do for IE to apply style rules to <foo> elements, and construct them appropriately in the DOM. Years ago Remy Sharp created the html5shiv project, which was the first library to essentially execute createElement for all of the new HTML 5 elements, including nav, article, footer, header, etc. html5shiv then allows IE to recognize all HTML 5 elements. 

Modernizr also "registers" all HTML 5 elements, meaning the HTML 5 MVC web application you build will work just fine on older versions of IE (as long as you leave Modernizer in your layout view). One note: you'll want to keep the script tag for Modernizr inside the <head> element. All the calls to createElement for new elements must happen before IE reaches the <body> tag.

Enabling HTML 5 elements is just one of the features Modernizr provides. In future posts we'll look at Modernizr's ability to detect features, and inject fallback scripts.