Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a best practice for generating html with javascript

I'm calling a web service that returns an array of objects in JSON. I want to take those objects and populate a div with HTML. Let's say each object contains a url and a name.

If I wanted to generate the following HTML for each object:

<div><img src="the url" />the name</div> 

Is there a best practice for this? I can see a few ways of doing it:

  1. Concatenate strings
  2. Create elements
  3. Use a templating plugin
  4. Generate the html on the server, then serve up via JSON.
like image 705
ckarbass Avatar asked Oct 21 '08 02:10

ckarbass


People also ask

Should I create HTML with JavaScript?

This, I believe, makes it far easier to maintain the code and quickly make changes to it because the markup is easier to read and trace. My rule of thumb is: HTML is for document structure, CSS is for presentation, JavaScript is for behavior.

What is the best practice for placing JavaScript in an HTML document?

Optimize JavaScript Placement Another good practice in using JavaScript with HTML is to place your JavaScript at the end of your HTML file if it is possible, between <script> tags, before the closing </body> tag, as you may notice from the above example.

Which of the following is a best practice for coding in HTML?

It is best practice to use HTML semantic elements for the proper assembly of your web page. Avoid using <divs> in place of HTML semantics. Do not use <div> elements to show headers and footers on your web page. Use semantic <header> and <footer> elements instead.


2 Answers

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.

like image 187
Jim Fiorato Avatar answered Oct 13 '22 21:10

Jim Fiorato


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.

like image 36
some Avatar answered Oct 13 '22 22:10

some