HTML & CSS
Article
By Craig Buckler

What’s New in Modernizr 2

By Craig Buckler

The second version of Modernizr has been released. Modernizr is probably the best-known and most widely-used feature detection library. As well as 40 browser tests and updated documentation, there are several new features to excite HTML5, CSS3 and JavaScript developers…

Conditional Resource Loading

yepnope.js is now integrated within Modernizr. It allows the page to conditionally load JavaScript or CSS files depending on support for one or more browser features. For example:


Modernizr.load({
	test: Modernizr.geolocation,
	yep : "geo.js",
	nope: "geo-polyfill.js"
});

In this situation, a browser which supports HTML5 geo-location will load geo.js whereas one without support will load geo-polyfill.js — which possibly contains extra code to implement similar functionality.

For more information, refer to Regressive Enhancement with Modernizr and Yepnope.

Media Query Testing

Responsive web design or zoom layouts have become increasingly popular techniques. In essence, the web page design uses CSS media queries to respond to the dimensions of the browser viewport. For example, perhaps a single column would be shown on a mobile device but the content would re-flow into two columns on a higher-resolution desktop browser.

Modernizr 2 allows you to test media queries in JavaScript, e.g.


if (Modernizr.mq("screen and (min-width:641px)")) // do something

This could be useful when loading further resources which wouldn’t be appropriate on a smaller screen, e.g. large banner adverts.

New Plugin API

You can now write your own test methods when a feature is not supported by Modernizr. The basic syntax is:


Modernizr.addTest(str, function);

Let’s create a simple example which detects whether the current window is a pop-up:


Modernizr.addTest("popup", function(){
	return !!window.opener;
});

If our page is running in a pop-up window, a .popup class is applied to the HTML element and Modernizr.popup will return true. Otherwise, the HTML element will have the class .no-popup.

Vendor Prefix Detection

The .prefixed() method returns the appropriate prefixed or non-prefixed name variant for a property supported by the browser, e.g.


var t = Modernizr.prefixed("transform");

The value of t would be “WebkitTransform” in webkit browsers and “MozTransform” in Firefox 4. Useful stuff.

Custom Build Tool

While it isn’t a new, it’s worth mentioning Modernizr’s custom build tool which allows you to pick the browser tests you require. It’s a great feature which can significantly reduce the size of the resulting script. I’d recommend similar modular facilities if you’re developing your own JavaScript libraries.

Do you use Modernizr? Will you start using it now?

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account