Juno Im
Juno Im

Reputation: 77

which one is faster when render HTML

  1. php return json, then javascript createElement to add data.

    type: 'POST',
    data: "do=view&start=0&stop=100",
    success:function(data){
        var parsedJson = $.parseJSON(data);
        var jExcel  = document.getElementById('jExcel');
        for(var i=0; i<parsedJson.id.length; i++) {
            var cell1 = document.createElement("input");
            var cell2 = document.createElement("input");
            cell1.setAttribute("type", "text");
            cell1.setAttribute("value", parsedJson.id[i]);
            cell2.setAttribute("type", "text");
            cell2.setAttribute("value", parsedJson.userName[i]);
            jExcel.appendChild(cell1);
            jExcel.appendChild(cell2);
            jExcel.innerHTML += "<br>";
        }
    }
    
  2. php return echo "<input type~~">

Upvotes: 0

Views: 785

Answers (2)

Christian
Christian

Reputation: 1577

I don't think you will find an answer for this that is 100% correct 100% of the time.

It comes down to the speed of downloading the html result vs the speed of java script DOM manipulation and this would vary depending on what variables are involved in the output, and how much data is to be produced etc.

In this case though, I would bet money that number two is the fastest case as 9 times out of 10, downloading the PHP response will be faster than DOM manipulation on the client side.

Go with method 2 unless you have to the time and know-how to accurately time these two methods.

I have to be honest, I have never seen anyone even consider method 1 and am interested in knowing why you have?

Upvotes: 1

Miguel M.
Miguel M.

Reputation: 421

The first one gives your more control on the DOM elements since it's being created and handled first time in the browser client.

The second alternative will execute on the server-side, relieving the browser client of that task, thus making it faster for the client.

All in all, it really depends on what you're trying to achieve. If you're just displaying some information, I would stick to the second one.

Upvotes: 1

Related Questions