Serving page as xhtml with original script

What’s wrong with this picture?

If you’re using Mozilla (or its derivatives) to view this page, it’s obvious: the script is not returning the requested image(s).

So what tripped up the script? I did some Googling and found the answer in this discussion. The long and short of it is that the document.write method doesn’t work in XML.

The obvious fix is to have two JavaScript files: one for browsers that handle the application/xhtml+xml MIME type correctly and another for browsers that don’t. To the code in the previous example we add a variable, $is_xml, the value of which is determined by what a browser accepts in the HTTP_ACCEPT header:

<?

if (isset($_SERVER["HTTP_ACCEPT"]) && stristr($_SERVER["HTTP_ACCEPT"], 'application/xhtml+xml')) {
  header('Content-Type: application/xhtml+xml; charset=ISO-8859-1');
  $is_xml = true;
} else {
  header('Content-Type: text/html; charset=ISO-8859-1');
  $is_xml = false;
}

?>

To call the appropriate script within <head>:

<?

if ($is_xml) {
  echo "<script type=\"text/javascript\" src=\"/replacement_moz.js\"></script>\n";
} else {
  echo "<script type=\"text/javascript\" src=\"/replacement.js\"></script>\n";
}

?>

Now open replacement.js and save it as replacement_moz.js, where we replace:

document.write('<link id="hide-flicker" rel="stylesheet" media="screen" href="' + hideFlickerCSS + '" />');

with:

var l=document.createElementNS("http://www.w3.org/1999/xhtml","link");
l.setAttribute("rel", "stylesheet");
l.setAttribute("id", "hide-flicker");
l.setAttribute("href", "' + hideFlickerCSS + '");
l.setAttribute("media", "screen");
document.getElementsByTagName("head")[0].appendChild(l);

and

document.write('<link id="print-text" rel="stylesheet" media="print" href="' + printerCSS + '" />');

with:

var l=document.createElementNS("http://www.w3.org/1999/xhtml","link");
l.setAttribute("rel", "stylesheet");
l.setAttribute("id", "print-text");
l.setAttribute("href", "' + printerCSS + '");
l.setAttribute("media", "print");
document.getElementsByTagName("head")[0].appendChild(l);

And that’s it! Let’s see if it runs.

DTR Test: About | As text/html