0

What is the best way to render html with ajax?

way1: initially have less html and put more dynamic html via ajax.

way2: initially have more html and put less dynamic html via ajax.

for e.g my html

<div id="div1">
   <div>
      <p id="p1">hello</p>
   </div>
<div>

way1:

initial html

<div id="div1">
</div>

dynamic html

<div>
   <p id="p1">hello</p>
</div>

way2:

initial html

<div id="div1">
   <div>
       <p id="p1"></p>
   </div>
</div>

dynamic html

hello

this example is small but i hope you are getting the context.So the question is which is best for front end performance. and additionally does the browser repaints the whole page when we dynamically add html via javascript?.

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
YoYo Honey Singh
  • 464
  • 1
  • 4
  • 21
  • 1
    Not quite get your idea, but it will be the best if the layout does not change dramatically during AJAX request. Read FOUC rule. – Raptor Dec 14 '16 at 07:19
  • You should try out Vue, Angular or React they can render HTML dynamically – Peachyz Dec 14 '16 at 07:29
  • what i'm trying to ask, is their some benefits of adding less content by ajax.Because the browser already paints the required containers and just adding some dynamic data to that conatiner? – YoYo Honey Singh Dec 14 '16 at 10:56

2 Answers2

1

It depends on the amount of HTML you are handling in your page. If you are building a page with lot of modules, then the best way is to follow load on demand style. ie: Initially just get the bare minimum HTML required to bring up the page, And only when the user wants to operate on any module, or get a report etc, you do a ajax call and get only the required content.

This also means you will not load your scripts and CSS that act on the future HTML elements in the initial page, keep all you references to external files in a separate HTML (partial page) and through ajax get this page only. So you will be loading the HTML, its scripts, its CSS on demand.

And to your question

does the browser repaints the whole page when we dynamically add html via javascript?.

No, the entire HTML is not redrawn. If that was the case then every operation in JavaScript on DOM would have been a huge hit on performance. I believe the language is well written keeping performance as priority.

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
0

It depends on case (like always ;)) but with AJAX rather you should get/receive only necessary values, in HTML you should have all tags that you need (some kind of template) and then just put there values received from request or other modified data by javascript.