Question

I'd like to load the Respond.js polyfill only for browsers that don't support media queries. I use RequireJS to manage my js files and Modernizr to detect feature support.

What's the best way to have RequireJS load Respond.js only when a browser doesn't support media queries?

I saw this answer and it worked but is there a better way to do this? As I add more polyfills I'll had to repeat this over and over?: RequireJS: Conditionally Load Polyfill Using Modernizr

My code looks like this and is wrapped around my main require statement:

if (Modernizr.mq('only all')) {
  require(['plugins/respond'], function(){});
}
Was it helpful?

Solution

The simplest way is to get the Modernizr package that includes Yepnope.js. Then you can load conditionally this way:

Modernizr.load({
    test: Modernizr.mq('only all'),
    yep: '',
    nope: 'plugins/respond.js'
});

Unfortunately, yes, you'll have to do this for every feature that you want to support with a polyfill. The yep property allows you to load a script when the feature is present.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top