loge.hixie.ch

Hixie's Natural Log

2004-08-04 13:40 UTC Why document.write() doesn't work in XML

Several people recently asked me why their scripts, which worked fine when they were using HTML, stopped working when they started using XHTML (and actually sent their markup with an XHTML MIME type).

There are plenty of reasons why that might happen. Not using the namespaced DOM Core methods is one, but few people use the DOM Core methods so it's rarely the cause. It could also be that their markup wasn't well-formed, but usually that's pretty obvious since the browser complains about it, and when people ask me, it's usually because the cause is subtle, so this is rarely it either.

It usually turns out that the reason their code is failing is that they used document.write(), which doesn't work in XML. Why is that?

XML requires that an XML process abort on any well-formedness error. Say you have the following:

<foo>
 <scrible/>
 </bar>
</foo>

Since the </bar> tag is unmatched, the entire document is not well-formed, so the UA has to abort and not display it.

But if we allow document.write(), then you could have things like this:

<foo>
 <script type="text/javascript" xmlns="http://www.w3.org/xhtml/1999"/><[!CDATA[
  document.write('<bar>');
 ]]></script>
 </bar>
</foo>

Now the document is still not well-formed, so it must still abort when it gets to the </bar> tag. But the problem is that if we process that document, then when we get to the script, we write out a <bar> start tag after the <script> block, and now when we reach the </bar> tag, it matches something! So the UA couldn't tell if it was well-formed or not.

So in order to remain compliant with XML, document.write() doesn't work on documents that are parsed with an XML parser.

Pingbacks: 1 2 3 4 5 6 7