Scripts in XHTML

I frequently come across people who aren’t aware of the problems with using scripts inside XHTML documents. One of these problems is particularly fatal because it can cause a well-formedness error, but it’s not seen as an issue when documents are served as text/html.

The problem is with the use of special characters like ampersands (&), less-than (<) and greater-than signs (>). Only the first 2 of those are actually fatal, but it’s good practice to escape the latter as well.

Note: This is not an issue if you use external scripts in a separate file, which is usally a better alternative anyway, but there are times when including scripts in the page itself is useful.

To illustrate the problem, here are some examples. The following is fine in HTML 4, but not in XHTML.

<script type="text/javascript">
  if (a && b) {
     // Oops! Ampersands cause well-formedness error in XHTML!
  }
</script>

For XHTML, that would need to be written like this.

<script type="text/javascript"><![CDATA[
  if (a && b) {
  }
]]></script>

Or this:

<script type="text/javascript">
  if (a &amp;&amp; b) {
    // Oops! JavaScript syntax error in text/html
  }
</script>

But now, when served as text/html (not XML), both the CDATA section and the escaped ampersands are going to cause JavaScript syntax errors. You can comment them out like this:

<script type="text/javascript">//<![CDATA[
  if (a && b) {
  }
//]]></script>

But it’s easier to just admit you’re not using XHTML and use HTML instead.