Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if Media Queries are present using Modernizr

I'm trying to detect whether media queries are present using Modernizr 2, then loading in respond.js if appropriate.

I've put this in my script.js file...

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

What am I doing wrong? I'm really surprised there isn't an example of how to do this with Media Queries on the Modernizr site. Here is the version of Modernizr I'm using...

http://www.modernizr.com/download/#-backgroundsize-borderradius-boxshadow-iepp-respond-mq-cssclasses-teststyles-testprop-testallprops-prefixes-domprefixes-load

like image 426
SparrwHawk Avatar asked Sep 18 '11 09:09

SparrwHawk


People also ask

How Does Modernizr work?

Modernizr is a JavaScript library that detects which HTML5 and CSS3 features your visitor's browser supports. In detecting feature support, it allows developers to test for some of the new technologies and then provide fallbacks for browsers that do not support them.

How does modernizr detect browser?

We can access various properties of this object 'Modernizr' for feature detection using “Modernizr. featureName”. For example, Modernizr. video will return “true” if the browser supports the video element, and false if the browser doesn't.

What is modernizr MQ?

Modernizr.mq allows for you to programmatically check if the current browser window state matches a media query.


1 Answers

That's because !!Modernizr.mq === true at all times... you're testing for the wrong thing!

As per the docs:

If a browser does not support media queries at all (eg. oldIE) the mq() will always return false.

But this: Modernizr.mq() is false too! You have to actually test for something. Here, the all keyword is just what you need (or only all as Paul suggests):

Modernizr.load({
  test: Modernizr.mq('only all'),
  nope: 'polyfill.js'
});

However, all custom builds of Modernizr 2.0.x with mq include respond.js, so you never really need to test this, except if you want to load another polyfill instead. In that case, you will need to disable/remove respond.js from your build.

Modernizr 2.5.x

With the arrival of Modernizr 2.5.x, the above is no longer true. The abbreviated changelog specifies that:

We no longer include Respond.js in the builder because it was creating crashing conflicts in IE8. If you still require Respond.js in your project, just include it manually.

This means Modernizr.mq('only all') may now return false...

like image 105
Félix Saparelli Avatar answered Sep 21 '22 13:09

Félix Saparelli