JavaScript AJAX – Best Way to Store Data from AJAX Calls

ajaxclient-sidejavascriptperformanceweb-applications

I am writing a web-application in which I am retrieving data's from server through AJAX requests and the generate HTML content dynamically.
I have some data to load, generate HTML from it and append into my web page.
Now I was thinking on two solutions:

1) Do AJAX call, generate HTML from response, set display: none to it when I need, and when I'll need it later, set display: block; instead and hide() other content I don't need to display (always dynamically generated).

2) Save AJAX response into variables, remove HTML generated before, re-generate from variable when I'll need it later.

I don't know if I explained it well, but I would like to know which is best practice in terms of client/server performance.

Best Answer

The first approach you suggest, rendering the HTML into a hidden div is reasonable, particularly if the information returned by the service is unlikely to change once it has been rendered and you don't need to manipulate the variable any further. This avoids rendering the content more than once. From your description, it sounds like this is the basic need that you need to fill. Note, if you use display:none, any size or position calculations you do within the rendered area will not work properly. So, if you are dynamically sizing or placing any elements, they may not render properly. For simple HTML, this probably won't be a problem.

If you need to manipulate the result after it is received, or you are making the request multiple times and need to render the HTML anew each time because the response may have changed, a better approach would be to parse the response into an object and render it into the HTML using a function taking the object as input, or even better, using a templating system like the one included in the Underscore.js library to render the HTML.