Hailwood
Hailwood

Reputation: 92691

Return HTML or build HTML using javascript?

I am returning data about contacts to build a list

the basic html looks like

{repeat:20}
<div class="contact">
  <a rel="123">FirstName LastName</a>
  <div class="info">
    {repeat:5}
    <div>
      <div class="infoLabel">Age:</div>
      <div class="infoPiece">56</div>
    </div>
    {endrepeat}
  </div>
</div>
{endrepeat}

The {repeat:20} is not actual code
That block of code is repeated 20 times

My question is.

What is more benificial:

  1. Create the markup server side, return the actual html.
  2. Return Json data with the information and build the list client side.


For the purpose of this discussion let us assume some constants

Upvotes: 9

Views: 4557

Answers (7)

Gonzalo Larralde
Gonzalo Larralde

Reputation: 3541

If you're planning to do intensive AJAX tasks, such adding new records, edit them on the fly, etc., then I suggest you to load an empty page, that calls an script that returns an array of dictionaries by JSON, and then using the Template (beta) system implemented in jQuery recently, or implement one yourself, having a hidden element, with spans/divs/tds tagged with classes, and cloning and filling it each time a new record arrives.

On the other hand, if you're going to keep this static, just use HTML.

This is how I manage templating. This is an efficient way because the DOM elements does exists in the DOM tree, and cloning is less expensive than parsing an string that contains the elements.

<html>
    <head>
        <script type="text/javascript">
            $(function() {

                $contactTemplate = $("#contact_template")
                function makeContactElement(data) {
                    var $newElem = $contactTemplate.clone(true)

                    $newElem.attr("data-id", data.id)
                    $newElem.find(".name").text( data.firstName + " " + data.lastName )

                    for(var i in data.info) {
                        $newElem.find(".info").append( makeInfoElement(data.info[i]) )
                    }

                    return $newElem
                }

                $infoTemplate = $("#info_template")
                function makeInfoElement(data) {
                    var $newElem = $infoTemplate.clone(true)

                    $newElem.find("infoLabel").text(info.label)
                    $newElem.find("infoPiece").text(info.piece)

                    return $newElem
                }

                $.getJSON('/foo.bar', null, function(data) {
                    for(var i in data) {
                        $("#container").append( makeInfoElement(data[i]) )
                    }
                })
            })
        </script>
        <style type="text/css">
            .template { display: none; }
        </style>
    </head>
    <body>

        <div id="container">
        </div>

        <!-- Hidden elements -->

        <div id="contact_template" class="contact template">
          <a rel="123" class="name"></a>
          <div class="info"></div>
        </div>

        <div id="info_template" class="template">
          <div class="infoLabel"></div>
          <div class="infoPiece"></div>
        </div>
    </body>
</html>

Then, when you create a new record, just fill a data object with the information, and you'll sure that all the element flow will be generic.

Using .clone(true) opens the door to make generic events instead of binding a live event, which is more expensive.

For example, if you want to make a button to delete a record:

<script ...>
...
$("#contact_template .delete").click(function() {
    var id = $(this).parents("contact").attr("data-id")
    $.post('/foo.bar', { action: delete, id: id }, function() { ... })
    return false
})
</script>
...
<div id="contact_template" class="contact template">
    <a href="#" class="delete">Delete</a>
</div>

Good luck!

Upvotes: 3

Serge Stepanov
Serge Stepanov

Reputation: 588

Since you are not worried about server-side load and have CPU cycles to spare, go ahead and let your backend do the bulk of the work. The application will be snappier and respond faster. You have to keep in mind network utilization, however. Throwing JSON strings back and forth is extremely efficient and reduces network load, but requires the client to do more work. As stated in this discussion, browsers are extremely fast these days. JavaScript implementations in Chrome, FF4 and IE9 are some of the fastest we have ever seen.

My suggestion is to do a small benchmark with your application as-is, and see how it performs. Try to hit the two variants with many requests to see things under load. It will really depend on your particular application.

Upvotes: 1

Keith
Keith

Reputation: 43064

It seems that you are asking for an opinion, not a specific answer to a technical question. So here's my opinion.

The trend these days is towards web applications, with more client-side functionality and off-line functionality. Therefore, I would do it client side and send JSON. That is also more scalable since the server side does less work.

Upvotes: 1

jAndy
jAndy

Reputation: 236162

As most of the times during web development, you need to decide what is more important to you.

If you're just after performance no matter what, it is of course faster to do all the render action on your server and just deliver HTML code. But this in turn, most times costs flexability plus, you've got more traffic over the wire.

On the other hand, just sending JSON data for instance and do the render stuff on the client, is much less traffic over the wire, but it's more CPU load on the clientside. Browsers (DOM + ECMAscript) have increased performance like a lot over the past years and month, so it is what lots of applications do.

But this is not the end of story. JSON is optimized, but not highly optimized. Again if you're really after performance you need to create your own transport of data. For instance

|box1|item1|item2

is less code then JSON notation

'{"box1": ["item1", "item2"]}'

This of course is highly specific, but it saves lots of traffic if we're going really big. I recommend the book High performance Javascript by Nicholas C. Zakas. Execellent book about this topic.

Upvotes: 8

Galen
Galen

Reputation: 30170

Page loading time wouldn't factor into my decision if i were you. I'd think about how easy it would be to maintain. I think doing it serverside would make things a lot easier. No need to have templates for your javascript to parse.

Upvotes: 1

Eric Petroelje
Eric Petroelje

Reputation: 60549

Personally, I would create it server side and return the html. The biggest reason being that otherwise your site is useless to anyone who has javascript disabled. It would also be largely invisible to search engines.

Upvotes: 2

david.wosnitza
david.wosnitza

Reputation: 763

i'd say do it server-side.... as JS might increase your page-loading time...

Upvotes: 1

Related Questions