0
\$\begingroup\$

I use the following code to populate my HTML with JSON. The problem is that I'm afraid this code will be inefficient if the number of records that I get from the service call are large (200 or more).

Are there ways I can change my code to make sure this won't be an issue? Or is my code fine as it stands?

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
    var jsonObj = {
        "products": [
            {
                "ImageName": "product1.png",
                "Description": "Yummy choco"
            },
            {
                "ImageName": "product2.png",
                "Description": "candy villa"
            },
            {
                "ImageName": "product3.png",
                "Description": "vanilla icecream"
            }
        ],
    }
    $(document).ready(function() {
        for(var key = 0; key < jsonObj.products.length - 1; key++) {

            var domStructure ='\
                <tr>\
                    <td>\
                        <img src="' + jsonObj.products[key].ImageName + '">\
                    </td>\
                    <td>'
                        + jsonObj.products[key].Description +
                    '</td>\
                </tr>';

            $('#tableProducts').find('tbody').append(domStructure);
        }
    });
</script>
</head>
<body>
    <table id="tableProducts"><tbody></tbody></table>
</body>
</html>
\$\endgroup\$
0

4 Answers 4

3
\$\begingroup\$

don't even really need jQuery for this task

here's one way to rework this script:

example jsfiddle

var domStructure = "";
    jsonObj = {
    "products": [
    {
        "ImageName": "product1.png",
        "Description": "Yummy choco"
    },
    {
        "ImageName": "product2.png",
        "Description": "candy villa"
    },
    {
        "ImageName": "product3.png",
        "Description": "vanilla icecream"
    }],
};

function getTableRow(img, desc) {
    return '\
        <tr>\
            <td>\
                <img src="' + img + '">\
            </td>\
            <td>' + desc + '</td>\
        </tr>';
}

for(var key in jsonObj.products) {
    domStructure += getTableRow(jsonObj.products[key].ImageName, jsonObj.products[key].Description);
}

document.getElementById('tableProducts').getElementsByTagName('tbody')[0].innerHTML = domStructure;

or if you keep jQuery method to set the table row markup use $('#tableProducts tbody') instead of $('#tableProducts').find('tbody'), no need to have jQuery fetch the first element then find the second vs letting it works it magic on one selector. it's about the same speed on the various selectors according to this jsperf.

Tests the following html setters:

  1. $('#tableProducts tbody').html(domStructure);
  2. $('#tableProducts').find('tbody').html(domStructure);
  3. $('#tableProducts').children('tbody').html(domStructure);
  4. document.getElementById('tableProducts').getElementsByTagName('tbody')[0].innerHTML = domStructure;

in the results the pure JS method jumps ahead on Firefox 9.0.1 and Safari 5.1.2

\$\endgroup\$
5
  • \$\begingroup\$ jspeft suggests, $('#tableProducts').find('tbody') is faster than $('#tableProducts tbody') and $('#tableProducts').children('tbody'). $('#tableProducts tbody') and $('#tableProducts').children('tbody') are almost same. \$\endgroup\$
    – Jashwant
    Jan 31, 2012 at 8:48
  • \$\begingroup\$ thanks for your help Mdmullinax. I am using jquery for other implementations on my project. is it fine to use the core javascript methodology only for this functionality?? \$\endgroup\$
    – Lokesh
    Jan 31, 2012 at 9:46
  • \$\begingroup\$ sure you can always use the pure javascript methodology, and you'll generally see a performance increase when you do but it can lead to additional development time and testing vs jQuery. However, if you're already using jQuery it may be more maintainable code if it's all consistently in jQuery. \$\endgroup\$
    – MikeM
    Jan 31, 2012 at 15:34
  • \$\begingroup\$ @Jashwant updated my answer with jsperf link \$\endgroup\$
    – MikeM
    Jan 31, 2012 at 15:35
  • \$\begingroup\$ yeap, there is no match for pure javascript :) \$\endgroup\$
    – Jashwant
    Jan 31, 2012 at 15:48
2
\$\begingroup\$

Even though your code may be doing proper output. What you did is not ideal way to doing this. Ideally, you should iterate the Json object and generate the HTML content. This is most optimized way.

Smart jQuery programmer code like this :)

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
        var jsonObj = {
            "products": [
                        {
                            "ImageName": "product1.png",
                            "Description": "Yummy choco"
                        },
                        {
                            "ImageName": "product2.png",
                            "Description": "candy villa"
                        },
                        {
                            "ImageName": "product3.png",
                            "Description": "vanilla icecream"
                        }
            ]
        };

        var htmlContent="";
        $.each(jsonObj["products"],function(key,val){   
           htmlContent+=("<tr><td>"+val["ImageName"]+"</td><td>"+val["Description"]+"</td></tr>");  
        }); 
     $('#tableProducts').find('tbody').append(htmlContent);
});
</script>
</head>
<body>
  <table id="tableProducts"><tbody></tbody></table>
</body>
</html> 
\$\endgroup\$
4
  • \$\begingroup\$ this is what i was looking for ... you are a smart programmer Umesh. Thanks a lot dude ! \$\endgroup\$
    – Lokesh
    Jan 31, 2012 at 9:35
  • \$\begingroup\$ @Umesh... want one more suggestion like rather putting the <tr><td> tags, can i dynamically create the markup? will it effect the performance of my code? please suggest. \$\endgroup\$
    – Lokesh
    Jan 31, 2012 at 9:58
  • \$\begingroup\$ is there any possibility to create the markup dynamically means creating '<tr><td>' on the fly ???? \$\endgroup\$
    – Lokesh
    Jan 31, 2012 at 11:22
  • \$\begingroup\$ It's possible. In current case, it will be of no use. We are just generating the code to put inside the table. It can be done in any ways. \$\endgroup\$
    – Umesh
    Feb 1, 2012 at 4:46
2
\$\begingroup\$

Just one suggestion,

Select tbody before loop. Currently you are selecting it again and again in loop.

Also, you should use,

  $('#tableProducts').find('tbody').append(domStructure);

children() search for direct descendants while find() looks for all descendants.

But surprisingly, jsperf.com suggests,

$('#tableProducts').find('tbody') is faster than $('#tableProducts tbody') and $('#tableProducts').children('tbody'). $('#tableProducts tbody') and $('#tableProducts').children('tbody') are almost same.

\$\endgroup\$
1
  • \$\begingroup\$ valid point Jashwant. Will incorporate this change. Thanks for your time :) \$\endgroup\$
    – Lokesh
    Jan 31, 2012 at 8:28
0
\$\begingroup\$

You are using google jquery library, why you don't use it like this:

    <script src="http://www.google.com/jsapi" type="text/javascript"></script>
    <script type="text/javascript">
        google.load("jquery", "1.7.1");
        //google.load("jqueryui", "1.7.3");
    </script> 

This is more dynamic and you can change the version of what you need.

I think this is an improvement you could make.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Is it the answer to this question ? \$\endgroup\$
    – Umesh
    Jan 31, 2012 at 7:51
  • \$\begingroup\$ Just a sugestion if you want to improve your code and like to use google jquery library \$\endgroup\$
    – Oscar Jara
    Jan 31, 2012 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.