1. Technology

JavaScript and XHTML

5. Don't Comment it Out


When JavaScript was first introduced only some browsers understood what the script tag meant. It was therefore necessary to place an HTML comment tag around any inline JavaScript in order for those browsers that didn't understand the script tag (such as IE2 and Netscape 1) to not display the javaScript as a part of the text content of the page.

Since browsers that do not understand what a script tag is for are no longer used to access the web using comments around inline JavaScript like that is no longer necessary but a lot of people writing JavaScript are used to doing it that way and it therefore continues to be done even though it doesn't achieve anything except to make the HTML file a few bytes larger.

Such a comment around JavaScript has never been necessary with XHTML since all browsers that understand XHTML have always known what a script tag is for (since JavaScript has been around for longer than XHTML has).

XHTML therefore treats a comment tag around the JavaScript differently from the way that HTML does. While in HTML a comment a HTML comment around the JavaScript code hides the JavaScript from the handful of early browsers that didn't understand the script tag while still allowing other browsers to see the JavaScript (unless you also wrap it in a JavaScript comment), XHTML treats a comment as a comment regardless of where it appears. So if you wrap your JavaScript inside an XHTML comment it is commented out just as effectively as if you wrapped it inside a JavaScript comment and so having the script inside either type of comment means that it will not run.

You should therefore never wrap inline JavaScript inside an XHTML comment since that has the same effect as not having the script there at all.

<script type="application/javascript>
<!-- // hide from all browsers
// JavaScript here is inside the XHTML comment and will not run
// --></script>

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. Don't Comment it Out

©2014 About.com. All rights reserved.