What other options for replacing entire HTML document via W3C DOM? What other options for replacing entire HTML document via W3C DOM? ajax ajax

What other options for replacing entire HTML document via W3C DOM?


I guess I will answer this with my own findings as I'm wrapping up my research on this.

Since the two browsers which have issues with one of these methods are both beta, I've opened bug reports which hopefully will resolve those before their full release:

I've also found pretty consistently that this...

document.replaceChild(newDomDoc, document.documentElement);

...is 2-10x faster than this...

var doc = document.open("text/html");doc.write(newStringDoc);doc.close();

...even when including the time needed to build the DOM nodes vs. build the HTML string. This might be the reason for the flicker, or perhaps just another supporting argument for the DOM approach. Chrome doesn't have any flicker with either method.

Note the subtle change of storing the returned document which circumvents the bug in Firefox 4.0b7.

Also note this added MIME type which the IE docs claim is "required".

Finally, Internet Explorer seems to have a bit of trouble resolving link tags that were built before the new document is swapped in. Assigning the link href back to itself appears to patch it up.

// IE requires link repairif (document.createStyleSheet) {    var head = document.documentElement.firstChild;    while (head && (head.tagName||"") !== "HEAD") {        head = head.nextSibling;    }    if (head) {        var link = head.firstChild;        while (link) {            if ((link.tagName||"") === "LINK") {                link.href = link.href;            }            link = link.nextSibling;        }    }}

One could cover all bases and combine them like this...

var doc = document;try {    var newRoot = newDoc.toDOM();    doc.replaceChild(newRoot, doc.documentElement);    // IE requires link repair    if (doc.createStyleSheet) {        var head = newRoot.firstChild;        while (head && (head.tagName||"") !== "HEAD") {            head = head.nextSibling;        }        if (head) {            var link = head.firstChild;            while (link) {                if ((link.tagName||"") === "LINK") {                    link.href = link.href;                }                link = link.nextSibling;            }        }    }} catch (ex) {    doc = doc.open("text/html");    doc.write(newDoc.toString());    doc.close();}

...assuming you have the ability to choose your approach like I do.