↑
Main Page
CDATA
alert("A is greater than B");
} else {
alert("A is equal to B");
}
}
</script>
This code raises two problems. First, developers aren’t used to writing code using XML entities. It makes
the code harder to read. Second, this is actually considered a syntax error in JavaScript because the inter-
preter has no idea what the XML entities mean. Using a CDATA section, it is possible to write JavaScript
code in its normal, readable syntax. The official way to include a CDATA section is as follows:
<script type=”text/javascript”><![CDATA[
function compare(a, b) {
if (a < b) {
alert(“A is less than B”);
} else if (a > b) {
alert(“A is greater than B”);
} else {
alert(“A is equal to B”);
}
}
]]></script>
Although this it the official way, remember that XHTML isn’t fully supported by most browsers, which
raises a major problem: This is a JavaScript syntax error because most browsers don’t recognize CDATA
sections yet!
The solution currently being used is a takeoff on the old “hide from older browsers” code. By using
single-line JavaScript comments, you can embed the CDATA section without affecting the syntax of
the code:
<script type=”text/javascript”>
//<![CDATA[
function compare(a, b) {
if (a < b) {
alert(“A is less than B”);
} else if (a > b) {
alert(“A is greater than B”);
} else {
alert(“A is equal to B”);
}
}
//]]>
</script>
This code now works in browsers that don’t support XHTML as well as those that do.
Like the use of the
type
attribute, the use of CDATA sections in this way is becom-
ing more prevalent as developers prepare for better support of XHTML in browsers.
Ultimately, however, it’s best to include JavaScript using external files in order to
avoid the CDATA problem altogether.
132
Chapter 5
08_579088 ch05.qxd 3/28/05 11:37 AM Page 132
Free JavaScript Editor
Ajax Editor
©
→