« Resnet adds ESPN | Prop 92 » |
For a while now, my website is using XHTML. That by itself is working fine.
However, recently, I decided to actually set the appropriate MIME type for browsers that understand it (pretty much every modern browser except IE...)
The PHP code looks like this:
function SetMimeType() { header("Vary: Accept"); if (stristr($_SERVER["HTTP_ACCEPT"], "application/xhtml+xml")) header("Content-Type: application/xhtml+xml; charset=utf-8"); else header("Content-Type: text/html; charset=utf-8"); }
So far, so good.
But then, I noticed some strange thing: all my code for writing dynamic text on the client side didn't work anymore.
It turns out that the Javascript code to write to the document, document.write, doesn't work if the MIME type is set to application/xhtml+xml.
The reason is that with this MIME type, the webpage is considered XML, and the XML parser can fundamentally not handle content changes while it is parsing the content.
The W3C has a short blurb on their website:
Does document.write work in XHTML?
No. Because of the way XML is defined, it is not possible to do tricks like this, where markup is generated by scripting while the parser is still parsing the markup.
You can still achieve the same effects, but you have to do it by using the DOM to add and delete elements.
A quick Google search came up with two pages (here and here) that discuss this problem in more detail, and that provide some code.
I've tried the code in the second link, and it worked fine in Firefox. Interestingly, though, only if the code is directly embedded in the page. Including it from a separate file like this:
<script type="text/javascript" src="write.js"></script>
unfortunately did not work.
But anyway, that's at least a way to get my rather simple document.write code to work again.