I have a JavaScript Object with some information in it.
I have 2 options I can think of to create the HTML from this object. I was wondering which one is the correct way of doing things of is this just all preference?
1) Loop through this array with JavaScript and create the HTML with Jquery?
2) Ajax post/get the object to PHP and loop through this object(php array) and create the HMTL that way? Then return a json encoded object back with the HMTL in it and append it to a div?
What I currently Do to build
var OutterDiv = $(document.createElement('div'));
for loop{
OutterDiv.append("<span>SOME INFO</span>");
var InnerDiv = $(document.createElement('div'));
for loop{
InnerDiv.append("<span>SOME INFO</span>");
InnerDiv.append("<span>SOME INFO</span>");
}
OutterDiv.append(InnerDiv);
}
$("#content").append(OutterDiv);
Why don’t you loop through the object and create an HTML string from JavaScript? Then insert that string wherever you need it? I believe this is the fastest way you can accomplish what you want do do. The main idea is that concatenating strings is faster than inserting DOM elements, and perhaps faster than the latency caused by an Http request.
** Edit **
Apparantly, IE is slower at string concatenation (big surprise) and using an array is better.
Example :
This is probably as fast as you can get.
** Update **
While performing the task of building HTML with JavaScript is still generally faster, after some testing, it seems that concatenating strings, or building arrays are not faster than creating text nodes. The test can be viewed and forked on jsfiddle.net or here it is for archiving pruposes :
Overall, while each method is more efficient under some conditions (lots of or few data, long or short strings, etc.), the DOM method seems generally faster in all cases.
So, there you have it. Thanks to GGG for the initial test case.