Related question When is the CDATA section needed in a script tag? , explains that the CDATA section is recommended when embedding scripts in XHTML documents. However, simply setting the XHTML document type to the test document is not enough. CDATA is still considered a syntax error.
According to this blog post , this is because the content type must match the doctype definition. The correct XHTML should have the following set of Content-type headers:
Content-type: application/xhtml+xml
if this is not specified and text/html sent instead, browsers will revert to HTML. Indeed, if I add this title to my test case, browsers will begin to correctly parse JavaScript inside CDATA, even when CDATA does not comment out.
This works for me (setting the header using PHP):
<?php header("Content-type: application/xhtml+xml"); echo '<?xml version="1.0" encoding="UTF-8"?>'; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script><![CDATA[alert('Hey!');]]></script> </head> <body> </body> </html>β
source share