Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  • Server load is not an issue (we are using a high performance server)
  • The returned data is for display purposes only (not to be manipulated)
  • We are not factoring in users without javascript enabled.
  • We are not factoring in any browsers < Internet Explorer 7
like image 248
Hailwood Avatar asked Feb 07 '11 22:02

Hailwood


People also ask

Can you return HTML in JavaScript?

This can be done using JavaScript, and there are different ways to go about it. In this article, we'll show you how to return HTML or build HTML using JavaScript.

What is return in HTML?

The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.

Which is best HTML or JavaScript?

JavaScript simply adds dynamic content to websites to make them look good. HTML work on the look of the website without the interactive effects and all. HTML pages are static which means the content cannot be changed. It adds interactivity to web pages to make them look good.

Can you replace HTML with JavaScript?

One very useful ability provided by JavaScript is the ability to replace the content of elements in an existing HTML document that was previously displayed, even empty elements. There are many reasons that a web designer may choose to take advantage of this ability but providing interactive pages is a likely goal.


4 Answers

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.

like image 60
jAndy Avatar answered Oct 23 '22 12:10

jAndy


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!

like image 29
Gonzalo Larralde Avatar answered Oct 23 '22 12:10

Gonzalo Larralde


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.

like image 38
Eric Petroelje Avatar answered Oct 23 '22 12:10

Eric Petroelje


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

like image 1
david.wosnitza Avatar answered Oct 23 '22 12:10

david.wosnitza