views:

61

answers:

1

Hi , I'm trying to build a POC to migrate a heavy JSF application to a stateless ajax/restful application . In the proccess i can't decide what is the best way of presenting the JSON data returned to the screen , i can see 2 major approaches one is to have templates and use something like prototype's toHTML() with them and the other is to build the objects in javascript and then use appendchild . the first one is much more easy to understand for a new person who has to maintain the code as the templates are very clear and easier to maintain (allso the skills needed to change the html in templates are lower) but from what i understand the appendchild method is better in regards to browser speed .

what is the preferable way to handle this and am i missing other points of comparison between the two ? append child is this a good compromise between the two ? are there any other ways to do this ?
P.S : to be clear i'm talking about client side manipulations only

A: 

Setting html directly with innerHTML is the fastest way cross-browser. It has some bugs, however, that you should keep in mind (tables, forms, etc.).

var html = [];

for (...) {
  html.push( PARTIAL_HTML );
}

element.innerHTML = html.join("");

UPDATE: The best way may be to test it for yourself:

function test( name, fn, n, next ) {

  var n = n || 100; // default number of runs
  var start, end, elapsed;

  setTimeout(function() { 
    start = Number(new Date());   
    for ( ; n--; ) {
      fn() 
    }
    end = Number(new Date());

    elapsed = end - start;

    // LOG THE RESULT
    // can be: $("#debug").html(name + ": " +  elapsed + " ms");
    console.log(name + ": " +  elapsed + " ms")); 

    next && next();
  }, 0);
}

test("dom", function() {
  // ...
});

test("innerHTML", function() {
  // ...
});
galambalazs
hi , the innerhtml benchh is 2 years old i don't know if this is still the case .. ?
amnon
I know it is, but if you're not sure you can always do the test yourself, see my update.
galambalazs
thanks , i will check . another problem i have with the innerhtml method is the fact i can't use some custom widgets like dojo grid etc... i can't find a good article online describing different approches to handle json , do u know of any ? thanks
amnon