« Resnet adds ESPNProp 92 »

document.write and XHTML

02/21/08

  12:21:00 by Joe, Categories: Miscellaneous

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.

No feedback yet


Form is loading...

This blog tries to capture all the gripes about UCI Resident Networking (Resnet) and the switch to UCI-managed Cable TV in on-campus housing.
This site is not affiliated with UCI or UCI Housing.
April 2024
Mon Tue Wed Thu Fri Sat Sun
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          
 << <   > >>

Search

  XML Feeds

blogging software