Modernizr ditched Yepnope.js: How to load your polyfill

I just discovered that the latest major release of Modernizr no longer includes yepnope.js to help you with simple conditional loads of polyfills.

For some time I’ve been using Enquire.js to handle media queries for JS. I love it! It’s simple. It works. It makes some complicated responsive designs much easier to implement.

The analytics for the sites I had previously been using Enquire with reflected a hip and happening demographic that didn’t require much support for legacy browsers (the matchMedia API used by Enquire isn’t supported on some older browsers). But I recently started a new job where it’s important to the mission of the organization to ensure as much functionality for older browsers as possible (there’s a substantial number of IE 8 users according to our analytics).

I followed Enquire’s instructions for ‘Deep support’ of legacy browsers by loading Modernizr, the media-match polyfill to support back to IE6, and a few lines of code for Modernizr to put the polyfill into action aaaaaand…nothin! Didn’t work. StackOverflow didn’t really have anything (which I’ve since attempted to remedy). The docs on Modernizr didn’t directly reference a change. I finally pieced together that the Yepnope.js script utilized and included previously in Modernizr had been deprecated with the release of version 3. So, that sucks: Yepnope made it really easy to load a JavaScript file (APPARENTLY but I’ll never know). And Enquire.js needs to update their docs.

The Modernizr docs don’t give an obvious solution for someone whose JS and jQuery skills are limited. Some googling brought me to David Walsh’s post on the jQuery getScript method and I put together a solution. I realized it might be helpful to put this info out there for someone like myself looking for a way to load polyfills with Modernizr who had or would have previously relied on the Yepnope part of the equation.

So, here it is:

Step 1: Modernizr & jQuery.

Download a build of Modernizr with your necessary tests included and load it. In my case it’ll just be ‘matchmedia’. You’ll also need jQuery.

Step 2: Write an if statement for your test.

//check if the browser supports your test
if (Modernizr.matchmedia){
//if it does: do something
console.log(‘Survey says: New Browser’);
} else {
//if it doesn’t: do something else
console.log(‘Survey says: Stanky Old Browser’);
}

Step 3: Test it. If it works: Load your polyfill with jQuery’s getScript method instead of printing a sassy console log message.

if (Modernizr.matchmedia){
//test matched, don't do anything
console.log(‘Nice Browser!’);
} else {
//oh no old browser: load polyfill
jQuery.getScript("/path/to/script")
.done(function() {
console.log('Script Loaded!');
})
.fail(function() {
console.log('Script Did Not Load!');
});
}

Step 4: Fire up Grandma’s PC and test it out on IE6.

That’s it! I hope this helps someone!