Is there a best practice for generating html with javascript Is there a best practice for generating html with javascript javascript javascript

Is there a best practice for generating html with javascript


Options #1 and #2 are going to be your most immediate straight forward options, however, for both options, you're going to feel the performance and maintenance impact by either building strings or creating DOM objects.

Templating isn't all that immature, and you're seeing it popup in most of the major Javascript frameworks.

Here's an example in JQuery Template Plugin that will save you the performance hit, and is really, really straightforward:

var t = $.template('<div><img src="${url}" />${name}</div>');$(selector).append( t , {     url: jsonObj.url,     name: jsonObj.name});

I say go the cool route (and better performing, more maintainable), and use templating.


If you absolutely have to concatenate strings, instead of the normal :

var s="";for (var i=0; i < 200; ++i) {s += "testing"; }

use a temporary array:

var s=[];for (var i=0; i < 200; ++i) { s.push("testing"); }s = s.join("");

Using arrays is much faster, especially in IE. I did some testing with strings a while ago with IE7, Opera and FF. Opera took only 0.4s to perform the test, but IE7 hadn't finished after 20 MINUTES !!!! ( No, I am not kidding. ) With array IE was very fast.


Either of the first two options is both common and acceptable.

I'll give examples of each one in Prototype.

// assuming JSON looks like this:// { 'src': 'foo/bar.jpg', 'name': 'Lorem ipsum' }

Approach #1:

var html = "<div><img src='#{src}' /> #{name}</div>".interpolate(json);$('container').insert(html); // inserts at bottom

Approach #2:

var div = new Element('div');div.insert( new Element('img', { src: json.src }) );div.insert(" " + json.name);$('container').insert(div); // inserts at bottom