Loading Tables Faster - J Query

Problem
You’re loading a JSON data object with 1,000 names and addresses and using jQuery to create a table with this data. It takes 5–10 seconds to create the table in IE 7—and that’s not even counting the download time.
Your JSON data is in this format:

Your JavaScript code is as follows:


And you have this HTML code in your document:

It works fine, resulting in the browser display shown in Figure:

resulting in the browser display

It’s just much too slow.

Solution

Combine several optimizations:

  • Insert a single <table>or <tbody>instead of multiple <tr>elements
  • Use .innerHTMLor .html() instead of DOM manipulation
  • Build an array with a[++i] and .join() it instead of string concatenation
  • Use a bare-metal for loop instead of $.each
  • Reduce name lookups
    The result is this new version of the code (using the same esc() function as before):

The new code requires the HTML code in your document to be changed to the following:

On one test system in IE 7, the new code runs in 0.2 seconds compared with 7 seconds for the original code. That’s 35 times faster!
Granted, the code is not as clean and elegant as the original, but your site’s visitors will never know or care about that. What they will notice is how much faster your page loads.

Discussion
Sometimes you’ll get lucky and find that one specific optimization is all it takes to fix a performance problem. Sometimes, as in this recipe, you’ll need several tricks to get the speed you want.
The biggest speed boost in this code comes from inserting a single <table>element with all its children in a single DOM operation, instead of inserting a lengthy series of <tr>elements one by one. In order to do this, you need to generate the entire table as HTML. That means you need to paste together a large number of strings to build the HTML, which can be very fast or very slow depending on how you do it. And with 1,000 items to loop though, it’s worth finding the fastest way to write the loop itself.
You may wonder, “Is this still jQuery code? It looks like plain old JavaScript!” The answer is yes, and yes. It’s quite all right to mix and match jQuery code with other javaScript code. You can use simpler jQuery ways of coding in most of your site, andwhen you discover the slow parts, you can either find faster jQuery techniques or use plain old JavaScript as needed for performance.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics