2

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);
3
  • It doesn't really matter how you get the html as long as you append it efficiently. For example, appending an entire document fragment or html string is more efficient than appending 1 element at a time in a for loop. Commented May 18, 2012 at 15:37
  • @Kevin B - So question I have is appending in that loop would be considered slow? But I dont really append to DOM until I build the DIV... Commented May 18, 2012 at 15:40
  • what you are doing is fine because you are appending to a document fragment, not the document. Commented May 18, 2012 at 15:49

3 Answers 3

2

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 :

var html = [];
for (...) {
   html.push( <some html content from your object here> );
}
$(selector).html(html.join(''));

// find the elements you need to handle and perform bindings here
// ex: $('#someelment').click(...);

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 :

function runTest(testFn, duration) {

    var endTime = +new Date() + duration;
    var runs = 0;
    var charCount = 0;

    while (+new Date() < endTime) {
        charCount += testFn();
        ++runs;
    }        
    teardown();

    //console.log(testFn.title, 'ran', runs, 'times.');
    $('#log').append($('<div></div>').text(testFn.title + ' ran ' + runs + ' times (' + (charCount/1000) + ' cps).'));
}

///

function teardown() {
    while (targetDiv.firstChild) {
        targetDiv.removeChild(targetDiv.firstChild);
    }
}

///

var testData;
var sample, sampleData;
function generateTestData() {
    testData = {};
    for (var i=0; i < (Math.random() * (sample[1]-sample[0])) + sample[0]; i++) {
        testData['item'+i] = randomString();
    }
}


function randomString()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789";

    for( var i=0; i < (Math.random() * (sampleData[1]-sampleData[0])) + sampleData[0]; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

function shuffle(arr) {
    var len = arr.length;
    var i = len;
    while (i--) {
        var p = parseInt(Math.random()*len);
        var t = arr[i];
        arr[i] = arr[p];
        arr[p] = t;
    }
    return arr;
};

///

var $targetDiv = $('#targetDiv');
var targetDiv = document.getElementById('targetDiv');

///

function jq() {

    var html = [];
    var count = 0;

    for (var key in testData) {
        count += testData[key].length;
        html.push('<div>' + testData[key] + '</div>');
    }

    $targetDiv.html(html.join(''));

    return count;
}

function inner() {

    var html = [];
    var count = 0;

    for (var key in testData) {
        count += testData[key].length;
        html.push('<div>' + testData[key] + '</div>');
    }

    targetDiv.innerHTML = html.join('');

    return count;
}


function dom() {

    var root = document.createElement('div');
    var node;
    var count = 0;

    for (var key in testData) {
        count += testData[key].length;
        node = document.createElement('div');
        node.appendChild(document.createTextNode(testData[key]));
        root.appendChild(node);
    }
    targetDiv.appendChild(root);

    return count;            
}

///

jq.title = 'jQuery .html';
inner.title = 'innerHTML';
dom.title = 'DOM';

///

sample = [10, 100];
sampleData = [100, 1000];
generateTestData();

var duration = 1000;
var testFn = shuffle([jq, inner, dom]);

$.each(testFn, function(k, fn) {
    setTimeout(function() { runTest(fn, duration); }, 0);
});
​

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.

Sign up to request clarification or add additional context in comments.

17 Comments

Maybe I'm reading this wrong, but I don't see how string concatenation followed by something like innerHTML would be faster than skipping the string concatenation step and just inserting DOM elements... Do you have some kind of performance test to back up this claim, or am I just misreading you?
I was going to ask the same thing? Ill add some sample code of whaT I am currently doing. I don't insert it until after I build
each time you insert an element into the DOM, the document gets reparsed and re-indexed. If you use innerHTML once, this process is done only once.
unless you need to handle events to a specific created element, there is no need to create jQuery-object-wrapped elements with each and every created elements.
|
1

Do it in javascript. If you already have the data in javascript, taking an extra trip to the server to have PHP do it (letting javascript broker that connection) is wasteful. If it was an intensive calculation, it might make sense to let PHP do it because of speed, but otherwise, seems like a waste.

Comments

0

You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.

1 Comment

in this way you should go for jqeury .append() or .html() or you can simply create html string in javascript and pass it on to ur html page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.