22

I am curious about people's experiences with replacing the entire document at runtime in an Ajax web app. It's rare, but I've found a few situations where the app requires an entire page rebuild and everything is present locally without needing another server round-trip.

I can easily prepare the new document as either a new DOM tree or as a String. So I'm evaluating the trade-offs for various approaches.

If I want to use the String approach this seems to work:

document.open();
document.write(newStringDoc);
document.close();

Most browsers do this just fine, but many have a slight flicker when re-rendering. I've noticed that on the 2nd time through Firefox 4.0b7 will just sit there and spin as if it is loading. Hitting the stop button on the location bar seems to complete the page render. (Edit: this appears to be fixed in 4.0b8) Also this method seems to prevent the user from hitting refresh to reload the current URL (it reloads the dynamically generated page).

If I use a new DOM tree approach (which has different advantages/disadvantages in flexibility and speed), then this seems to work:

document.replaceChild(newDomDoc, document.documentElement);

Most browsers seem to handle this perfectly fine without flicker. Unfortunately, IE9 beta throws "DOM Exception: HIERARCHY_REQUEST_ERR (3)" on replaceChild and never completes. I haven't tried the latest preview release to see if this is just a new bug that got fixed. (Edit: this appears to be fixed in RC1.)

My question: does anyone have a different approach than either of these? Does anyone have any other caveats where perhaps a particular browser fundamentally breaks down with one of these approaches?

Update: Perhaps this will add context and help the imagination. Consider a situation where an application is offline. There is no server available to redirect or refresh. The necessary state of the application is already loaded (or stored) client-side. The UI is constructed from client-side templates.

I believe that Gmail uses iframes embedded within a root document. It appears the starting document for at least some of these iframes are just a bare HTML5 document which the parent document then manipulates.

Using an iframe would be another variant on the requirement to replace the current document by replacing the entire child iframe or just its document. The same situation exists though of what approach to attach the new document to the iframe.

mckamey
  • 17,359
  • 16
  • 83
  • 116
  • 2
    "I've found a few situations where the app requires an entire page rebuild" - this should never be *required*, it probably means you need to redesign your application. It's possible to modify just about everything on a page without needing to actually replace the document itself. – casablanca Nov 28 '10 at 17:01
  • 8
    With all due respect that is not your call. There are times where you need to build an entirely new document. Gmail does this for instance. – mckamey Nov 28 '10 at 17:02
  • 3
    If you need to rebuild the entire document, why don't you use the feature browsers have had for ages, made specifically for that purpose: reloading the page? – Bart van Heukelom Nov 28 '10 at 17:09
  • 1
    @McKAMEY: I don't know if and when Gmail does this, but that doesn't make it right. If you really need to build a new document, then it's essentially a *different* application, so why not just load a different page? – casablanca Nov 28 '10 at 17:11
  • 7
    The page is dynamically built from client-side state. I would appreciate it if people would stick to the question rather than questioning the reasoning for the approach. Once I have all the trade-offs to the approach then I will evaluate if it is the path I want to take. I don't need help making that evaluation. – mckamey Nov 28 '10 at 17:12
  • @McKAMEY: No offence meant. I believe I roughly understand what you're trying to do, so let me ask if you must necessarily do this in the current document. If not, I would suggest that you use `window.open` + `document.write` to load your generated page in a new window. That would solve the refresh problem you're facing and also result in better user experience than replacing the current document and having no way to go back. – casablanca Nov 28 '10 at 17:22
  • For the scenario in mind I am looking to replace the current document. The flicker is less of a jarring experience than a new window popping up. Where Gmail does this I believe is with iFrames embedded within the original document. That would be a hybrid of what you and I are proposing. – mckamey Nov 28 '10 at 17:29

1 Answers1

21

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 repair
if (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.

mckamey
  • 17,359
  • 16
  • 83
  • 116
  • 2
    Where is the implementation of `newDoc.toDOM()`? – Gili Oct 24 '14 at 22:24
  • 2
    @Gili I had to refresh myself now 4 years later. `newDoc.toDom()` and `newDoc.toString()` are whatever you are doing to generate your new doc. That last snippet was from https://bitbucket.org/mckamey/duel/raw/tip/duel-js/target/duel.js – mckamey Oct 31 '14 at 00:12
  • I get "May not add a Document as a child" when I try to replace the document. I was so close :( Can I fix that? – france1 Oct 21 '22 at 07:50