JSON to DOM or innerHTML?

I have this code:

try {
    var _o, _l, i, _d = new Array(), _c;
    _o = JSON.Parse( Request.Response );
    for ( i = 0, _l = _o.length; i < _l; i++ ) {
        _d[ i ] = document.createElement('div');
        _c = document.getElementById('comentsContainer');
        _c.removeChild( _c.firstChild );
        _d[ i ].className = 'comment-user';
        _c.appendChild( _d [i] );
    }
}
catch ( w ) {
    console.log( w );
}

      

The question is, is this better or should I use innerHTML?

ADD: object to parse:

"comments" : [
  { "user" : "foo", "comment" : "foo", "date" : "foo/foo/bar", "id_comment" : "bar" },
  { /* the same as above x10 */ }
]

      

Please note that I want to parse every object from every array for a DOM element

+3


source to share


2 answers


Since you already have a structural representation of the data here (instead of raw HTML for parsing), I would say your approach (using DOM manipulation techniques) makes more sense than using a built around approach .innerHTML

. Has .innerHTML

shown performance gains in some cases , but I'm not sure that's the case with modern browsers with decent JavaScript engines. Also, the big payoff you could get from dumping the HTML into a property innerHTML

is that you still need to generate that HTML from your view JSON

, which will also take time. Since you have to process the object JSON

, using DOM manipulation methods is a sane design approach.



+2


source


I would say manipulation DOM

is a cleaner approach: innerHTML

- this is the bit spaghetti code

where you mix markup language with behavior (JavaScript) and you don't have a clear structure at the end.Also, in most modern browsers it is DOM API

faster or equivalent innerHTML

in terms of performance - unfortunately IE and Opera are wrong:

http://jsperf.com/innerhtml-or-dom/4



So go to DOM APIs

, maybe you can clean up and optimize a bit of your code (for example, you don't have to do getElementById

every loop to get a reference to the Container comments, you can get it from outside, and also not of course why you remove the first child every time. when you add a comment it seems to me that you can probably delete the comment added earlier, in which case it can be optimized too).

+1


source







All Articles