Protecting Scripts

It is common practice to enclose scripts and style sheets in comments (between <!-- and -->). Unfortunately, XML software thinks of comments as unimportant information and may simply remove the comments from a document before processing it. To avoid this problem, use an XML CDATA section instead. Content enclosed in <![CDATA[...]]> is considered simple text characters and is not parsed (for more information, see Chapter 7). For example:

<script language="JavaScript">
<![CDATA[
...JavaScript here...
]]>
</script>

The problem with this method is backward compatibility . HTML browsers ignore the contents of the XML CDATA section , while XML browsers ignore the contents of comment-enclosed scripts and style sheets. So you can’t please everyone. One workaround is to put your scripts and styles in separate files and reference them in the document with appropriate external links. The common practice is to avoid CDATA and comments altogether and keep scripts and style externalized. Although not required, it is heavily recommended as part of XHTML and document management.

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.