Validating Page with Javascript Code Inside

For those who insert javascript code in pages and want to validate as XHTML: With HTML pages on the web you can just include the required Javascript between tags. When you validate the HTML on your web page the Javascript content is considered to be CDATA (character data) that is therefore ignored by the validator. The same is not true if you follow the more recent XHTML standards in setting up your web page. With XHTML the code between the script tags is considered to be PCDATA (parsed character data) which is therefore processed by the validator.

To fix this problem we can do one of two things. The simplest way, particularly if the Javascript contains more than just one or two lines, is to make the Javascript external to the page resulting in their being nothing between the script tags to stop the page validating.

If you want to keep Javascript code inside your page then place the Javascript code within a CDATA tag like this:

What is important here is to place CDATA tags in between /* */ chars. The problem is that some older web browsers don't understand the CDATA tag and so this breaks your Javascript in those web browsers. Fortunately, Javascript multi-line comments start and finish with characters that do not cause validation errors.

We can therefore comment out the CDATA tag in so far as the Javascript processors within the web browsers are concerned while still leaving the Javascript content defined as CDATA as far as the validator is concerned.

Now our Javascript code is handled correctly both by newer browsers and validators that actually understand the XHTML DTD as well as by older web browsers that don't understand XHTML and interpret everything on the page as HTML.