Manish Kumar
Manish Kumar

Reputation: 10482

Dynamically assign value to dom

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

Answers (2)

Schleis
Schleis

Reputation: 43700

Depends on the use case, both solutions have advantages and disadvantages.

The first method:

  • Doesn't load the elements until you need them
  • But it also has JQuery creating the element in memory rather than modifying elements on the page.

The second method:

  • Isn't creating the elements so modifying the markup is a little easier as we aren't looking for html in the js.
  • Now we have to remember to hide the elements if we don't want the user to see them

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

Paras
Paras

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

Related Questions