Reputation: 10482
I have a html page which will show the user profile username,place,about etc. I am getting the value using ajax in jquery. Now i have question how to assign retrieved value to the DOM:
First method would be wait till i get data then dynamically create dom and append to target div
$.ajax({
url: "profiledata",
type: "POST",
success:function(data){
$("<div><label>"+data.name</label><br/>
<label>"+data.place</label></div>").appendTo("target div");
}
In this method more append of string will happen so i doubt about memory consumed by the process.
Second method will be just use id to assign the value:
$.ajax({
url: "profiledata",
type: "POST",
success:function(data){
$("#uname").text(data.name);
$("#place").text(data.place);
}
<div><label id="uname"></label><br/>
<label id="place"></label></div>
Which one will be efficient in terms of loading the page i.e. lighter code and page Did i mentioned some write approach? or some better solution is there?
Upvotes: 2
Views: 199
Reputation: 43700
Depends on the use case, both solutions have advantages and disadvantages.
The first method:
The second method:
Which method that I would use, would depend on varying factors. Generally, I prefer the second because then when I want to modify the markup, I am not looking in the javascript.
Upvotes: 1
Reputation: 3067
Manipulating DOM repeateadly often involves overhead. From that perspective the first method seems more appropriate.
As far as the speed of the ajax call is concerned, the data is retrieved in the same fashion in both the methods, you could use .ajaxStart()
and .ajaxStop()
to have 'loading' kind of effect.
Upvotes: 1