Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strategies for rendering HTML with Javascript

I take a fat JSON array from the server via an AJAX call, then process it and render HTML with Javascript. What I want is to make it as fast as humanly possible.

Chrome leads over FF in my tests but it can still take 5-8 seconds for the browser to render ~300 records.

I considered lazy-loading such as that implemented in Google Reader but that goes against my other use cases, such as being able to get instantaneous search results (simple search being done on the client side over all the records we got in the JSON array) and multiple filters.

One thing I have noticed is that both FF and Chrome do not render anything until they loop over all items in the JSON array, even though I explicitly insert the newly created elements into DOM after every loop (as soon as I have the HTML). What I'd like to achieve would be just that: force the browser to render as soon as it can.

I tried deferring the calls (every item from the array would be processed by a deferred function) but ran into additional issues there as it seems that the order of execution isn't guaranteed anymore (some items further down the array would be processed before other items before it).

I'm looking for any hints and tips here.

like image 789
Tomas Kohl Avatar asked Apr 30 '26 07:04

Tomas Kohl


2 Answers

try:

  • push rows into an array, then simply

     el.innerHTML = array.join("");
    
  • use document fragments

    var frag = document.createDocumentFragment();
    for ( loop ) {
        frag.appendChild( el );
    }
    parent.appendChild( frag );
    
like image 178
25 revs, 4 users 83% Avatar answered May 01 '26 20:05

25 revs, 4 users 83%


If you don't need to display all 300 records at once you could try to paginate them 30 or 50 records at a time and only unroll the JSON array as those sub-parts are required to be displayed through a pager or a local search box. Once converted you could cache the content for subsequent display as users navigate up and down the pages.

like image 43
bjg Avatar answered May 01 '26 19:05

bjg