Templates In jQuery Load With More Than 1000 Records Of Data Using JQuery Templates

In this write-up, I will explain about jQuery templates. You might be facing performance issues when loading more than a 1000 records in your webpage using jQuery.

The solution is jQuery templates.

Let us have some JSON data in your file. The below screen shows the script of JSON data in file.

You can find the attached code which contains code and JSON data file. Now, we have more than 1000 records in the JSON file.

I will now explain the jQuery Templates concept by fetching the data from the JSON file and displaying it in table by creating templates.

Step1

Create an index.html page. Given below is the code.

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title></title>  
  6.     <meta charset="utf-8" />  
  7.     <script src="jquery-1.10.2.min.js"></script>  
  8.     <script src="jquery.tmpl.min.js"></script>  
  9.     <script src="OurCustomScript.js"></script>  
  10. </head>  
  11.   
  12. <body>  
  13.     <table cellpadding="1" cellspacing="1" border="1">  
  14.         <thead>  
  15.             <tr>  
  16.                 <th>ID</th>  
  17.                 <th>Name</th>  
  18.                 <th>Contact</th>  
  19.                 <th>Date of birth</th>  
  20.             </tr>  
  21.         </thead>  
  22.         <tbody id="tbodyData"> </tbody>  
  23.     </table>  
  24. </body>  
  25.   
  26. </html>  

You can download the template plugin jquery.tmpl.min.js from here.

And in the above html, the JS file OurCustomScript.js is our custom JavaScript code.

Step2

Now, create a JavaScript file with the name OurCustomScript.js and add the below code in it.

  1. $(document).ready(function() {  
  2.     $.get("1000PlusRecords.json"function(responseData) {  
  3.         // Now prepare the custom template as shown below. The name 'prepareRowsToDisplay' is the template name  
  4.         $.template('prepareRowsToDisplay''<tr><td>${id}</td><td>${name}</td><td>${contact}</td><td>${dateOfBirth}</td></tr>');  
  5.         // Now once done with template preparation, pass your template and JSON data to '$.tmpl' function and then append to your table.  
  6.         $.tmpl('prepareRowsToDisplay', responseData).appendTo('#tbodyData');  
  7.     });  
  8. });  

In the above jQuery code, I have added the comments also to make the code more understandable. Now, run your index.html page, you will see the result as expected, as shown in the screenshot below.

Ebook Download
View all
Learn
View all