Detect HTML5 & CSS 3 features in your ASP.NET Web Forms, MVC, or Razor Pages with Modernizr-Rachel Appel on Software Development

Share with friends!

  

Detect HTML5 & CSS 3 features in your ASP.NET Web Forms, MVC, or Razor Pages with Modernizr

Tags: Modernizr, HTML, HTML5, MVC 3, ASP.NET Web Forms, ASP.NET Web Pages, jQuery

Over the course of web history, browser detection, rather than feature detection, has been the de facto way to customize the browsing experience. However, this is an antiquated technique which is also very error prone, making the ability to deliver targeted markup & content difficult, at best. As browsers continue to evolve and release new versions, the list of capabilities that you need to worry about can grow exponentially. However, Modernizr aims to change that.

What can Modernizr do for you?

Modernizr

Modernizr is a JavaScript library that you can use to perform feature detection of emerging web technologies, in particular, feature sets found in HTML5 and CSS 3. In addition to its core feature detection library, Modernizr also offers the following features:

  • A tiny footprint (about 16k if you use everything)
  • Simple to use API
  • Asynchronous script loading
  • Back filling with polyfills & shims (see below)
  • Ways to test your own features not included in the Modernizr library with tests
  • Integrates with other libraries, such as yepnope.js and respond.js

Modernizr Overview

Visit Modernizr.com where you can select which tests you want to download and use. Modernizr detects over 40 features including the new popular CSS attributes, HTML5 elements, and other APIs, as illustrated in the image below:

Modernizr features

Use this utility to generate minified script(s) to include in your \Scripts folder as the production version.

For development, download and reference Modernizr's uncompressed development file, weighing in at 42k. If you prefer, but only for development purposes, you can point to the Microsoft CDN development version of the .js file. Currently, Modernizr's production scripts do not exist at the popular Google or Microsoft CDNs. Modernizr is gaining popularity and momentum, and it's entirely reasonable to speculate that it will be hosted at one or more of the major CDNs soon, so you may want to check the CDNs regularly for updates.

Once you've decided which script to use, you can start using Modernizr.

Setting up Modernizr

There is very little you need to do to use Modernizr.

Add a <script> tag inside the <head> tag [1], and reference the CDN or a downloaded Modernizr script.

The code below demonstrates a standard HTML document head section, including Modernizr in the script references.

<!DOCTYPE html>
<html class="no-js">
<head>
    <meta charset="utf-8" />
    <title>Trying out Modernizr</title>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.0.6-development-only.js " type="text/javascript"></script>    
</head>

You'll also want to modify the <html> element by inserting a class attribute and setting it to "no-js". Modernizr uses this as a fallback for browsers that do not support JavaScript.

Once you've prepared your project to use the Modernizr library, it's time to dig in and see how it works.

How Modernizr Works

During the Modernizr startup process, the initialization code performs the following tasks:

  1. The script creates a global Modernizr object, which contains a property for each feature that Modernizr exposes, along with a few methods, most notably for adding tests so you can extend Modernizr.
  2. The script sets up integration with yepnope.js, a conditional resource loader that allows you to optimize page performance by loading scripts only when you need them.

A great way to see Modernizr in action is to use it in a simple HTML page, then investigate it in debug mode using debugging tools in a browser. Open the IE F12 Developer Tools and navigate to the Script tab, then select the Modernizr script from the dropdown list. You can then set a breakpoint at the end of the file. This is when Modernizr is ready to return the Modernizr object, so it's fully populated and easy to investigate. 

IE Developer tools with Modernizr

Switching over to the HTML tab in the developer tools will reveal the <html> element at runtime that Modernizr creates to expose supported features.

Use IE F12 Tools to investigate Modernizr's HTML modifications

Here's the complete output from the screenshot highlight above:

<html class= "js no-flexbox canvas canvastext no-webgl no-touch geolocation postmessage no-websqldatabase no-indexeddb hashchange no-history draganddrop no-websockets rgba hsla multiplebgs backgroundsize no-borderimage borderradius boxshadow no-textshadow opacity no-cssanimations no-csscolumns no-cssgradients no-cssreflections csstransforms no-csstransforms3d no-csstransitions fontface generatedcontent video audio localstorage sessionstorage no-webworkers no-applicationcache svg inlinesvg smil svgclippaths">

Fortunately, you won't see this output in View Source, but you can see it while using the developer tools of just about any browser - it works the same in IE, Firefox, & Chrome. That's because the code in the Modernizr.js file works with the document.documentElement property, which is part of the XML DOM, not the HTML DOM. You can scan the Modernizr script file to reveal various lines of code that use the documentElement property.

Another great way to see how Modernizr works is to investigate the annotated source code online at http://modernizr.github.com/Modernizr/annotatedsource.html.

Now you're ready to start using Modernizr's powerful feature detection library by writing plain JavaScript, jQuery, or any client side JS library of your choice, to go along with any server side framework of your choice, such as Web Forms or MVC.

Modernizr & ASP.NET Development: Web Forms/MVC/Web Pages

Since Modernizr is just a JavaScript library, it works with all three ASP.NET development platforms: ASP.NET Web Forms, ASP.NET MVC, and ASP.NET Web Pages, so let's investigate each...

ASP.NET Web Forms

You can use NuGet to download, install, and upgrade your Modernizr scripts, by choosing References->Add Library Package Reference from Solution Explorer, or choosing the Add Library Package option from the Visual Studio Project menu. This command installs a development version of the Modernizr script that you can use, by downloading the script and adding the appropriate code to your Master Page.

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebApplication1.SiteMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" class="no-js">
<head runat="server">
    <title></title>
    <link href="Styles/Site.css"  rel="stylesheet" type="text/css" />
    <script src="../Scripts/modernizr-2.0.6.js" type="text/javascript"></script>
 <script src="../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
 <script src="../Scripts/juqery-ui-1.8.11.js" type="text/javascript"></script>
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

 Pro Tip: Consider changing both the <!DOCTYPE html PUBLIC...> and the <html> elements, included by default in the in Web Forms templates, to the new, lightweight, HTML5 versions.

<!DOCTYPE html>
<html class="no-js">

Add some code to any Web Form that uses the Modernizd Master Page to test any property of your choice, and for this example, we'll test to see if IE 9 supports local Web Storage.

<script type="text/javascript">
    if (Modernizr.localstorage !== null) {
        $("h1").text("This browser supports local storage");
    }
    else {
        $("h1").text("This browser does not support local storage");
    }
</script>
 
Viewing the results shows that Modernizr does work, and that Web Storage support exists in IE9.

SNAGHTML280921e

ASP.NET MVC

ASP.NET MVC3 project templates include the Modernizr script references for those who have installed either the MVC 3 Tools Update or the Web Standards Update (note: the WSU requires VS2010 SP1). When you create a new ASP.NET MVC 3 project, Visual Studio adds the Modernizr .js files to the \Scripts folder and adds the necessary <script> tags to the Layout Page (\Views\Shared\_Layout.cshtml).

<!DOCTYPE html>
<html class="no-js">
<head >
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/modernizr-2.0.6.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>

<script src="@Url.Content("~/Scripts/juqery-ui-1.8.11.js")" type="text/javascript"></script>

</head>

Alternatively, you can use NuGet to download and install the Modernizr scripts, much the same way you would do so for Web Forms, and as always, manual installation is an option.

You can then write code to detect features, like the below example demonstrating if the browser supports the Geolocation API.

<script type="text/javascript">

if (Modernizr.geolocation)

$("h1").text("Hello, Modernizd World, I can find you with Geolocation!");

</script>

The code above creates the following results:

SNAGHTML2625b64

ASP.NET Web Pages

You can manually download Modernizr for use in your ASP.NET Web Pages apps. After downloading, add the Modernizr scripts to your project, then add script references and code modifications to the _SiteLayout.cshtml page. When working with Razor pages you can use Html Helpers such as the @Href helper.

<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
    <meta charset="utf-8" />
    <title>My ASP.NET Web Page - @Page.Title</title>
    <link href="@Href("~/Styles/Site.css")" rel="stylesheet" />
    <script src="@Href("~/Scripts/modernizr-2.0.6.js")"></script>
 <script src="@Href("~/Scripts/jquery-1.5.1.js")"></script>
    <link href="@Href("~/favicon.ico")" rel="shortcut icon" type="image/x-icon" />
</head>

After the leading code is setup in the Layout Page, test out a Razor page by adding code that checks for a feature, in this case <canvas>.

<script type="text/javascript">

if (Modernizr.canvas) {

$("h1").text("This Modernizd browser supports the canvas element!");

}

</script>

Run the page from WebMatrix to verify Modernizr is working, and the <canvas> element is supported by IE 9.

SNAGHTML2885675

Summary & Resources

Modernizr is a quick and easy way to detect modern web technologies with a few lines of script, and Modernizr works well with all three ASP.NET technologies. Browser detection is OUT! Feature detection is IN!

Related Posts:

For more on the IE developer tools, see my list of blog posts tagged as IE Developer Tools.

HTML5 Web Storage (local and session storage)

HTML5ify your ASP.NET MVC Applications

Find & install 3rd party libraries lightning fast with NuGet for Visual Studio 2010

HTML5 and HTML tagged Blog posts

Footnotes:

[1] Modernizr.com suggests: "For best performance, you should have them follow after your stylesheet references. The reason we recommend placing Modernizr in the head is two-fold: the HTML5 Shiv (that enables HTML5 elements in IE) must execute before the <body>, and if you’re using any of the CSS classes that Modernizr adds, you’ll want to prevent a FOUC." (flash of unstyled content) -Modernizr.com

2 Comments

Add a Comment