Sunday, December 26, 2010

Another hack to render heavy HTML pages

when HTML page is loaded, browser needs to do a lot work. It has to parse HTML, build elements collections (so things likegetElementsByTagName() can work faster), match CSS rules, etc., etc. And then, finally, render all those elements—you may know this process as repaint. Repainting is one of the slowest process in browsers.

One quick solution is that we don’t need to show all 500KB text at once, we can pick a first few sentences and push them to the screen so the user can start reading while browser parses the rest of the page.

How we do same ??

To make all this large text invisible to the browser, all we have to do is to comment it:-

    <p>Well, LARGE HTML HERE ...</p>


When the text content was commented out, the page parsing took quickly.
So, we have a commented text, what now? Actually, HTML comment is not just a hidden code chunk, it’s a DOM node which can be easily accessed. Now we need to find this node and parse its content into a DOM tree:-
var elems = document.body.childNodes;

for (var i = 0, il = elems.length; i < il; i++) {
  var el = elems[i];
  if (el.nodeType == 8) { //it’s a comment
    var div = document.createElement('div');
    div.innerHTML = el.nodeValue;
    // now DIV element contains parsed DOM elements so we can work with them
Since such plain text parsing doesn’t require browser to do CSS matching, repainting and other stuff that it normally does on page parsing, it also performs very fast.

No comments:

Post a Comment