Joined: Aug 27, 2002 Posts: 16987 Location: Kansas
Posted:
Tue Mar 13, 2007 10:20 pm
Making JavaScript Compatible with XHTML
See this post for the background to this FAQ:
Only registered users can see links on this board! Get registered or login to the forums!
XHTML is subject to the same syntactical rules as XML. Because of this, an XHTML processor treats the characters < < and & & as markup, even if they reside inside a script block. Since the < and & characters are also used by the JavaScript language, this creates a conflict. When an XHTML processor sees these characters within the JavaScript code of a script block, it attempts to parse the JavaScript code as if it were markup, which causes the XHTML parser to fail.
You can get around this conflict and make all JavaScript code compatible with XHTML by placing the JavaScript code within a CDATA section. A CDATA section in XML/XHTML starts with the characters <![CDATA[ and ends with the characters ]]>.
Any characters within the starting and ending element of a CDATA section are not treated by the XML/XHTML processor as markup, thus preventing a conflict.
Here is an example of how to declare JavaScript code within a CDATA section so that it is compatible with XHTML. Note that I have intentionally misspelled script as scr!pt to avoid a conflict with NukeSentinel(tm).
<scr!pt type="text/javascript">
//<![CDATA[
alert("<This is compatible with XHTML>");
//]]>
</scr!pt>
Note that JavaScript source code must be placed within the opening and closing elements of the [b]CDATA section. The CDATA section itself should be commented out with a JavaScript single-line comment // as in the example above. This is so that the JavaScript interpreter does not interpret the CDATA markup as JavaScript, which would cause a JavaScript error.
JavaScript code that is imported into an XHTML document from an external source file is always compatible with XHTML. So, for example, any code you place into the external file external.js and import into an XHTML file via the src attribute of the script tag will be valid. Here is an example of how to import the file external.js:
View next topic View previous topic
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum