Friday, August 27, 2010

Hiding JavaScript Statements from Older Browsers

Browsers that were distributed before the script tag was invented will correctly ignore tags they do not "understand" such as the script tag. However, the JavaScript statements in between the script tags will appear to these browsers as plain text. Most often older pre JavaScript browsers will therefore render the JavaScript statements as paragraph text. This can be quite alarming if a nicely designed page suddenly appears to someone as a long stream of meaningless code.

To get around this, the code can be hidden inside an HTML comment tag. An HTML comment tag looks like this:

<--This is a comment.-->

The opening <-- part of the tag is usually placed on the next line right after the opening <SCRIPT> tag and the closing part of the comment tag on the line just before the closing </SCRIPT> tag. Just to make things more complicated the closing part of the HTML comment tag must be preceded by the // characters that precede a JavaScript comment. Here is a short example:

<SCRIPT Language="JavaScript">
<!--


// -->
</SCRIPT>

JavaScript statements are placed on the line after the <!-- and on lines before the // -->


No comments:

Post a Comment