Skip to content
Related Articles

Related Articles

How can JavaScript codes be hidden from old browsers that do not support JavaScript ?

View Discussion
Improve Article
Save Article
  • Last Updated : 17 Feb, 2022

Nowadays all modern browsers support JavaScript, however, older browsers did not support JavaScript. In this article, we will learn how we can hide JavaScript code from running in older browsers.

Approach: After opening the <script> tag, we will use a one-line HTML style comment without any closing character ( <!– ). We will then write the JavaScript code that is to be hidden from older browsers. We will use the closing character with comment ( //–> ) before we close the script with the </script> tag.

Syntax:

<script>
    <!--
         // Your JavaScript code
         // that is hidden from older browser
         
         console.log("Hello Geeks");
    //-->
</script>

Example: In this example, the background color will be changed to red if the browser supports JavaScript, else it will remain yellow.

HTML




<!DOCTYPE html>
<html lang="en">
<body bgcolor="yellow">
    <h1 style=
        "text-align: center;
         font-size: 3rem;">
      Hello Geeks
    </h1>
    <script type="text/javascript">
        <!--
            document.bgColor ="red";
        //-->
    </script>
</body>
</html>


Output: We can see that the old browser will ignore JavaScript code and will treat JavaScript code as an HTML comment, but modern browser easily access JavaScript code and will not create any problem.

  • When the browser does not support JavaScript:
  • When the browser supports JavaScript:

Note: If the IDE gives a syntax warning using the above approach, we can add a JavaScript comment before the first HTML style comment to prevent it from doing so.

<script>
 //<!--
    // Your JavaScript code
     // that is hidden from older browser
         
     console.log("Hello Geeks");
 //-->
</script> 
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!