What’s the best way to embed scripts in an (X)HTML page?

Updated: May 2009

What this is about

There’s some discussion on what exact syntax, use of comments, CDATA sections and character sequence–escaping is necessary or useful when embedding JavaScript code in HTML and XHTML pages.

These tests try to determine that, while doing away with some practices that were recommanded in the past and may not be relevant anymore, and paving the way for HTML 5 and XHTML 5

The criteria used here will be:

Know issues with JavaScript code within the script HTML element

For the sake of simplicity, we would put or JavaScript code directly between the <script> and </script> tags, maybe declaring the type attribute if it’s required, and move along.

The HTML or XHTML specifications don’t any additional step. But problems arise when the JavaScript code contains some character sequences that will make a conforming SGML or XML parser choke. Such character sequences are:

Test pages

HTML 4.01

XHTML 1.0

HTML 5

The W3C markup validator doesn’t have a XHTML 5 validation mode (yet?), so i didn’t test with XHTML5. Since XHTML5 is (/will be) XML, my guess is that one would get the exact same results as with XHTML 1.0 served as application/xhtml+xml.

Temporary conclusions

Bottom line

There’s less trouble with HTML. In HTML 5, there’s no trouble at all. In HTML 4, you need to escape occurrences of </, but if you forget the worse you’ll get is a validation error.

If you write XHTML, you’re probably serving XHTML 1.0 as text/html, so you shouldn’t get parse errors, but may till get validation errors. Solution: use a CDATA section, but use JS comments so that browsers will ignore those markers.

That’s a bit backwards, right? It’s almost like serving different code to browsers (“hey, Mr browser, please don’t see that CDATA section!”) and to validation tools (“hey, Mr W3 validator, see, i used a CDATA section!”).