Best Way To Detect If Visitors Browser Supports JavaScript

There are many ways you can add different styles for JavaScript enabled browsers and different for the browsers that don’t have JavaScript enabled. But most approaches have some problem or the other. Below are some of the approaches people follow, along with the problems they come with.

  1. 1. Using The <noscript> Tag

    Most people use the noscript tag, and it works like a charm in most cases. But there are many discussions going all over the web to stop using it. Some of them are here and here.

    With HTML5, you can even add the noscript tag to the head of the document, prior to that, it was limited only to the body tag. This gives it another edge over all other methods, since you can now declare styles even before the content of the page has loaded.

  2. 2. Using JavaScript To Add A Class

    This method works well for the most part, but the problem comes when you will want to style the content for the browsers that don’t support JavaScript. Since JavaScript will add a new class, you have no way to know if it will be added or not.

  3. 3. Using JavaScript To Replace A Class

    This method is an extension of the second method, and likely to be the best one. To have a solution for the problem in method two, we give a class to an element first, and then replace that class with another class. This way, you can style the elements using the former class for the browsers that don’t support JavaScript, and use the latter class, for the browsers with JavaScript support.

    Implementation

    1. Add a class, say, ‘no-js‘ to the <html> tag. You can style all your elements with this class. This class will only be available on browsers with no JavaScript support.
    2. Add this code in your JavaScript file, or inside the <script> tags. Make sure this code loads in the head of the document.

      document.getElementsByTagName("html")[0].className = document.getElementsByTagName("html")[0].className.replace(/(?:^|\s)no-js(?!\S)/g, ' js')

      This code will replace all the instances of ‘no-js’ with ‘js’ from the class attribute of the HTML tag.

    3. Now you can style your elements with the html.js selector too. This selector will only be available if the JavaScript is enabled on the visitors browser.

This is what I am implementing on all my projects. Do let me know if you have any better way of doing it.

Related Post