Enclose inline javascript in valid XHTML

July 11th, 2009 by Supriya Agnihotri Jagani § 1

With HTML pages on the web, you can just include the required Javascript between <script> and </script> tags.

When you validate the HTML on your web page, the Javascript content is considered to be CDATA (character data), therefore ignored by the validator. But this is not true, if you follow the XHTML standards in creating your web page.

With XHTML, the code between the script tags is considered to be PCDATA (parsed character data) which is processed by the validator. Because of which, you cannot include Javascript between the script tags on your page(I mean inline javascript), without breaking your web page; as far as the validator is concerned.

This problem can be fixed by 2 different ways.

Make the Javascript external to the page, so that there is nothing between the script tags to stop the page validating.

Moreover, If it is just one or two lines of code, then it is probably not worth making an external script. So you would prefer to keep the content between the script tags and ask the validator to ignore the particular code. This can be done by placing the Javascript code within a CDATA tag like this:

script1

This fixes the validator.
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, while leaving the Javascript content defined as CDATA as far as the validator is concerned. We do it like this:

script2

Now your Javascript code will be handled correctly by both newer browsers and validators that actually understand the XHTML DTD as well as by older web browsers that don’t understand XHTML and consider everything on the page as HTML.

Tagged: , ,

§ One Response to “Enclose inline javascript in valid XHTML”

What's this?

You are currently reading Enclose inline javascript in valid XHTML at Digicorp.

meta

Share