Search code examples
javascriptaptana3

Hiding JavaScript from displaying in old browsers


I am trying to learn JavaScript from a book. The first chapter of the book says to use the following format to support older browsers that don't support JS. What it actually does is simple, it uses HTML comment tag to hide script from browsers that don't support JS. My doubt here is this code works fine for me in all the browsers but is showing error in Aptana Studio 3. Now I understand that the error is due to Aptana considering "<" as a relational operator but how can I resolve this error?

<script>
    <!--
        //some JS code over here...
    //-->
</script>

Error(Syntax Error: Unexpected Token) coming at :

<!--

Solution

  • I'm aware that this does not answer your question directly, but the truth is that this simply does not need to be done. If a browser does not know how to interpret the JavaScript, almost all browsers will ignore the code anyway. Furthermore, adding the <!-- // --> can be dangerous as well for the following reasons, given by Matt Kruse:

    • Within XHTML documents, the source will actually be hidden from all browsers and rendered useless
    • It is not allowed within HTML comments, so any decrement operations in script are invalid

    For a more detailed explanation, I recommend you check out this documentation about the best practices for JavaScript and this question that explains why using HTML comments in JavaScript is bad practice.

    If for whatever reason you still want to show content to the user if they have JavaScript disabled (or can't run it because of an old browser), use a <noscript> tag

    If you truly are deadset on commenting out your JavaScript then use this code snippet instead, which shouldn't give you the error:

    //<!--
    
    //-->
    

    If you have any more questions feel free to ask.