Last Updated: February 25, 2016
·
2.929K
· Slava Bogu

Simple JavaScript detection for your CSS

It is debatable whether there is any significant number of users browsing the Web with scripting disabled - and, with major analytics solutions such as Google Analytics being based on JavaScript, it's not exactly easy to keep track of the exact count, either.

The basic vehicle for reacting to disabled scripts has long been the <noscript> tag - an inelegant vestige from simpler days which can do little else than load a banner requiring users to enable scripts in order to proceed (don't do that!); or, a little better - a 'no js' stylesheet:

<noscript><link rel="stylesheet" href="nojs.css"></noscript>

However, you can easily make your main stylesheet JS-aware, not to mention save a request, if you ditch the <noscript> and begin your HTML with the following code instead:

<html class="no-js">
    <head>
        <script>
            var _h = document.getElementsByTagName("html")[0];
            _h.className = _h.className.replace(/\bno-js\b/,'has-js');
        </script>

All this does is replace the no-js class name with has-js using a simple regular expression. If JavaScript is disabled, the replacement simply wouldn't take place and the no-js class would stick. In fact, the HTML5 Boilerplate does something quite similar.

Now you can use the .no-js and .has-js selectors in your CSS and style elements accordingly. As always, bear progressive enhancement in mind when building your pages: even if your application relies strongly on client-side scripting, there is a tangible performance benefit of rendering a page's initial contents on the server. For more discussion on that subject, check out Nicholas Zakas' quite sobering presentation.

3 Responses
Add your response

Useful one, when some one do not want to use heavyweights like Modernizr.

But I really hope these techniques of JS detection and having an alternate experience for JS disabled case go away for the goodness of web. Fortunately, it will happen sometime, as Firefox already has removed the option to disable JavaScript from GUI (though, one can still do so via config).

over 1 year ago ·

Thanks for the slides link! I smiled at 19th slide. Guess I pushed Backbone too hard.

over 1 year ago ·

Useful tip!

Btw: instead of document.getElementsByTagName("html")[0] you can use document.documentElement.

over 1 year ago ·