Saturday, November 11th, 2006
document.write and xhtml
<>p>Sam Ruby knew that document.write doesn't work well with XHTML so he went to find the best solution.His context:
Because Google AdSense depends on document.write, the net result is that I only serve ads to users of browsers that don’t support XHTML, which increasingly means that only IE users see ads.
His solution:
The solution is to use createElementNS instead. So far, so good. The only piece left to the puzzle is where to append the child that you created. If you simply do a document.appendChild, the new element ends up at the end of the document. There doesn’t seem to be a property which indicates the current node in the tree at the time of the parse. But in cases like adsense, you generally want the widget put in place.
The code:
-
-
var pos = document;
-
while (pos.lastChild.nodeType == 1) pos = pos.lastChild;
-
pos.parentNode.appendChild(...);
-
Could document.write be redefined if in an xhtml document to parse into a tree and append?
Related Content:











crazy!
Only in the case where both the enclosing document and string are separately well formed. As Ian points out, that’s not necessarily always the case, but not supporting document.write at all simply because you might start a tag outside the script and close it inside the script is like saying that you won’t support division because the denominator might be zero.
What about just doing this (or something similiar)?
document.write = function(e){
var span = document.createElement(‘SPAN’);
span.innerHTML = e;
document.body.appendChild(span);
}
In XHTML, there is no
document.body…Hawt! Gotta remember this one.
@ Mark,
this is what I tried out yesterday, too ;) But it doesn’t work as well as “native” document write. If you include a js file, the content is not executed. E.g. an alert(1) is made in native mode, but not in all browsers for overwritten version of document.write. I will work meticulously.
Andi
I talk about including a JS script by document.write, e.g.
document.write(”);
XHTML, document.write, and Adsense
After some recent discussion concerning the use of document.write() in XHTML documents served with the doctype “application/xhtml+xml” I decided to revisit the problem. An issue with the solutions proposed by Sam and Ajaxian is that they aren’t real…
document.write and xhtml
what if we give the script tag an id and drill it down from the document then append?
I will use JSON for this so that it is universal to all browsers and doc types.
For example:
var AdSense;
//this one return an object that has a method that does the…
there is no document.body in xhtml?
document.write() support for XHTML: http://weston.ruter.net/projects/xhtml-document-write/