HTML & XHTML: The Complete Reference (Osborne Complete Reference Series)

 <  Day Day Up  >  

The last topic that should be considered a core aspect of HTML is the use of comments in an HTML document. The contents of HTML comments are not displayed within a browser window. Comments are denoted by a start value of <!-- and an end value of --> . Comments can be many lines long. For example,

<!-- Document Name: Sample HTML Document Author: Thomas A. Powell Creation Date: 1/5/00 Last Modified: 5/15/03 Copyright 2000-2003 Demo Company, Inc. -->

is a valid comment. Be careful to avoid putting spaces between the two dashes or any additional exclamation or dashes points in the comment. Comments are useful in the <head> of a document to describe information about a document, as the previous example suggested. Comments might also be useful when trying to explain complex HTML markup.

Comments also can include HTML elements, which is very useful for hiding new HTML elements from older browsers, and is commonly used with <style> and <script> elements, discussed in Chapters 10 and 14, respectively. Recall that a typical browser will output the contents of any tag it doesn't understand onscreen. Thus, we may want to hide the contents of certain tags from nonsupporting browsers. For example, consider trying to hide a style sheet's contents from an older browser. The <style> element might occur in the <head> of the document and contain various style rules, as shown here:

<style type="text/css"> h1 {font-size: 48pt; color: red;} < /style>

A simple use of an HTML comment could mask the content from nonsupporting browsers like so:

<style type="text/css"> < !-- h1 {font-size: 48pt; color: red;} --> < /style>

In this case, style sheet-aware browsers are smart enough to know to look within a comment found directly inside the style element, whereas older browsers would just skip over the comment, and nothing would happen. The use of comments to mask script code is slightly different as the closing --> symbols are valid code under JavaScript. In this case, hidden script code is wrapped in <!-- //-->. The close comment is preceded with a // because // is a JavaScript comment that hides the --> from the script interpreter.

<style type="text/javascript"> < !-- alert( " Hello I am JavaScript"); // --> < /style>

Unfortunately, this comment-out trick does have some problems. Under strict interpretation of XHTML, you should use a CDATA section to mask the content, as shown here:

<script type="text/javascript"> <![cdata[ alert("Hello I am JavaScript"); ]]> </script>

It's interesting that this is not supported in the 6 and 7. x generation browsers so far; thus, the traditional hiding approach should be used if scripts are embedded in XHTML documents. However, in reality, linked scripts should be used wherever possible to more cleanly separate markup from programming logic.


 <  Day Day Up  >  

Категории