Introduction
HTML5 support is increasing in the newer browser versions. However, developers need to ensure that any HTML5 pages work correctly in older browser versions also. That requires the detection of the supported features in the user's browser client and makes provisions when features in use are not supported on the client browser.
Whether a new feature is supported or not, is detected by querying the DOM for the property and by creating instances of the DOM objects - there isn't a one-line answer to this question. You need to check various objects in the DOM depending on the feature you are looking for and by testing the existence of properties or success in creating or setting certain elements, figure out if the specific HTML5 feature is supported or not.
Introducing the Modernizr
Quoting the definition from Modernizr.com
"Modernizr is an open-source JavaScript library that helps you build the next generation of HTML5 and CSS3-powered websites."
The Modernizr can be used to detect if an HTML5 feature is supported on the client browser or not.
Note that the Modernizr does not add any additional support for HTM5 than what the client browser supports. It is a detection tool.
Steps
(1) Download the latest version
(2) Include this script tag in the <head> element
<script src="modernizr.min.js"></script>
(3) No other initialization action is required. A global object named "Modernizr" is now available and it exposes Boolean properties for each of the features that it can detect.
If the feature is supported on the browser, the Boolean property is set to true.
Sample code to detect Geolocation support on the client browser
- if (Modernizr.geolocation) {
- //yes! Geolocation is supported
- ..
- }
- else
- {
- //umm.. no geolocation support detected
- ...
- }
One step further
In combination with detecting supported features using the Modernizr library, you can use libraries such as Modernizr.load() to provide conditional resource loading. You can thus include scripts that do provide support when legacy browser support is lacking. "JavaScript shim that replicates the standard API for older browsers" is called a polyfill. This would enable you to plug in advanced new features in legacy browsers.
Resources
Conclusion
You can detect HTML5 features by writing scripts that check against the DOM. The Modernizr library simplifies this task without adding much performance load to your code. The MVC3 tools update includes Modernizr scripts for HTML5 feature detection.