title: What other options for replacing entire HTML document via W3C DOM?
body: <p>I am curious about people's experiences with replacing the <em>entire</em> 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 <em>everything</em> is present locally without needing another server round-trip.</p>
  
  <p>I can easily prepare the new document as <em>either</em> a new DOM tree or as a String. So I'm evaluating the trade-offs for various approaches.</p>
  
  <p>If I want to use the String approach this seems to work:</p>
  
  <pre><code>document.open();
  document.write(newStringDoc);
  document.close();
  </code></pre>
  
  <p>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. (<strong>Edit:</strong> 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).</p>
  
  <p>If I use a new DOM tree approach (which has different advantages/disadvantages in flexibility and speed), then this seems to work:</p>
  
  <pre><code>document.replaceChild(newDomDoc, document.documentElement);
  </code></pre>
  
  <p>Most browsers seem to handle this perfectly fine without flicker. Unfortunately, IE9 beta throws "DOM Exception: HIERARCHY_REQUEST_ERR (3)" on <code>replaceChild</code> and never completes. I haven't tried the latest preview release to see if this is just a new bug that got fixed. (<strong>Edit:</strong> this appears to be fixed in RC1.)</p>
  
  <p><strong>My question:</strong> 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?</p>
  
  <p><strong>Update:</strong> 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.</p>
  
  <p>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.</p>
  
  <p>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.</p>