Alex Rivera | Logout

Detecting when styles disabled

Asked 2011-01-21T12:30:47.667
9

What's the best way to detect, with JS, if the user has disabled your stylesheets? Is there a reliable way even?

Edit
Report

2 Answers

1

I would have a small, empty div sit on the screen. When the page loads, use JS to check the 'display' property of that div. If it's 'none', then your css has successfully been loaded. If not, they may have to turned off / changed your styles.

answered 2011-01-21T14:29:08.297
1

Assuming your primary external or inline stylesheet is loaded before the script, you can use this:

if (document.styleSheets.length){} // stylesheets are disabled

https://developer.mozilla.org/en-US/docs/DOM/document.styleSheets

It's IE5+ compatible too as per: http://www.jr.pl/www.quirksmode.org/dom/w3c_css.html

The caveat is that, if styles are turned off after the window has loaded (which only causes a browser repaint), the document.styleSheets object won't change on the fly. Additionally, as noted in the comments below, this will not work for Firefox when using the View -> Page Style -> No Style feature, for which styles are still loaded, just not applied to the view.

To detect the initial state across browsers, or changes on window.onresize, it can be done with a style reset on the body, with the following code placed after <body> or in a DOMContentLoaded event:

if (document.body.clientWidth !== document.documentElement.clientWidth) {
  // Styles are disabled or not applied
}

This works if you use body { margin: 0; } in your stylesheets (with no particular custom width), because it makes the body element the same width as documentElement (a.k.a. the <hmtl> element) while styles are active.

When styles are turned off or disabled, the body.clientWidth will revert to the browser's default body width, which always has a margin ( answered 2013-04-03T05:43:32.817

Your Answer