Invalid XHTML when adding JavaScript code to HTML pages

It’s a common problem to have a hard time validating Strict (or even Transitional) XHTML when using JavaScript on pages and usually the problem is because of using in our script of identical characters as those used by HTML, such as “< ", which means "less" in JavaScript.

The solution is adding of CDATA section, in each section we'll include our JavaScript code.
E.g.:

<script type="text/javascript">
<![CDATA[
var Ann = 12;
var John = 25;
if (Ann < John) {
window.alert("Ann is smaller than John!");
}
]]></script>



Now that we solved the page validation issue we got into another problem: the JavaScript we did write doesn’t execute! This is happened because the JavaScript code is altered by using our CDATA section tags.
The solution for this new problem is to wrap CDATA section tags into the comment tags:

<script type="text/javascript">
/*<![CDATA[*/
var Ann = 12;
var John = 25;
if (Ann < John) {
window.alert("Ann is smaller than John!");
}
/*]]>*/</script>

Still there is another, elegant, method to avoid all these problems, by using an external script file, which in this case will not interfere with our (X)HTML tags and of course will help us later on, saving our time of coding or copying the script on all pages we want that JavaScript to apply. Using an external file for our JavaScript will save our time in code debugging as well.

Tags : , ,

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

24 Comments

Leave Comment