2

I need to use javascript to detect whether a page is responsive. On a galaxy note 3, here are the values for a non-responsive and a responsive pages:

non-responsive: 
window.innerWidth:980 
clientWidth:980 
screen.width:640 

responsive: 
window.innerWidth:640 
clientWidth:640 
screen.width:640 

So is it correct to say that if clientWidth == screen.width then it is responsive, else it is non-responsive?

1
  • Nope. That just means the page is zoomed in or out. Commented Dec 21, 2013 at 8:49

1 Answer 1

3

As you know, there's an important feature used in responsive design call media query, with which browser can switch alternative CSS rules for different screen resolutions to make page "responsive".

You can enum CSS rules in Javascript using document.styleSheets. And CSS like

@media all and (max-width:1023px) {
    /* some styles */
}

will add some instances of CSSMediaRule in cssRules collection. Here's my detection code. Works in Chrome and Safari.

function isResponsive() {
  if (document.styleSheets || (typeof window.CSSMediaRule).match(/function|object/)) {
    // find avaliable style sheets
    return [].some.call(document.styleSheets, function(css) {
      if (!css.cssRules) {
        return false;
      }

      // find avaliable rules
      return [].some.call(css.cssRules, function(rule) {
        if (rule instanceof CSSMediaRule) {
          return [].some.call(rule.media, function(media) {
            return !media.match(/print/i);
          });
        }
      });
    });
  }
  // There's no avaliable style sheet, or the browser doesn't support media queries
  return false;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Cool.. Thanks! :) Just need to add if (r == null) continue; after r = s[i].cssRules;
Nice script but note it won't pick up any cross domain CSS files (e.g. those served by a CDN) so isn't entirely accurate. Also, you might want to check if the media rule isn't a @media print rule, as they have nothing to do with how responsive a page is.
@RobCampo @media print is now excluded
this now just gives exception when there is cross origin css

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.