tags:

views:

76

answers:

7

I'm trying to think of the most efficient way to add html to my page. I currently have:

jQuery("<tbody><tr class='section toggle-minus'><td colspan='3' class='toggle' id='make-"+id+"'>"+name+" (0)</td></tr></tbody>");

And then I add that to the page.... is there a more efficient way or is this pretty much it?

+1  A: 

Other than what you are doing, there is also html() method.

Sarfraz
+1 Yeah, and the html() method..
skajfes
+1  A: 

That is likely the most efficient way in terms of speed. jQuery lets the browser parse the HTML and that's fast... faster than DOM manipulation, in many cases.

Personally I don't like making HTML strings and having to deal with escaping user input and whatnot, so I often define this little extra method:

$.fn.create = function(name) {
    return $(document.createElement(name));
};

You can use that combined with other jQuery functions to create any HTML structure

$.create("tbody").append(
    $.create("tr").attr("class": "section toggle-minus").append(
        $.create("td") /* et cetera */
    )
)

It's a bit of a mouthful though, one day I'll surely implement a better element building method for jQuery.

Matti Virkkunen
A: 

I would say that this is pretty much it. As I understand it, it is just important that you minimize the number of DOM insertions.

skajfes
A: 

Or this way:

$([
'<tbody>',
    '<tr class="section toggle-minus">',
        '<td colspan="3" class="toggle" id="make-"', id, '">', name,' (0)','</td>',
    '</tr>',
'</tbody>'
].join(''));
San4ez
This is taking the slowest approach and making it slightly faster.
Stephen
+2  A: 

Actually, the fasted way to create an element with jQuery is to use this:

$(document.createElement('tbody'));

Creating an element like this $('<tbody></tbody>'), is a bit slower than the above method.

Here is the most optimized way to do what you are doing:

UPDATED

jQuery(document.createElement('tbody')).append(
    jQuery(document.createElement('tr')).append(
        jQuery(document.createElement('td'))
            .addClass('toggle')
            .html([name," (0)"].join(''))
            .attr({
                'colspan' : '3',
                'id' : ['make-',id].join('')
            })
    ).addClass('section toggle-minus')
);

The very last thing you would do is append it to the document. The joins are used because ie6/7 garbage collection stinks when concatenating.

Stephen
Fixed a typo, should be good now. **Yikes** I was coding too fast. Fixed two more typos.
Stephen
This is probably faster for creating single elements, but are you sure it's faster for a whole bunch of elements? At least a while back, `innerHTML` was way faster than any DOM manipulation. I wonder if anyone's done benchmarks on this using modern browsers.
Matti Virkkunen
That's a good question, I too wonder. I'm off to google it for an hour. ;)
Stephen
I've used this method to create many elements by mixing in clever uses of `.clone()` and cascading the `.attr` and `.addClass` methods. Basically you start with one element, add all of the common attributes it shares with other elements, clone it, then start adding the final attributes, all before insertion. It was pretty fast when I was done.
Stephen
+1  A: 

There are several jQuery templating plugins. I'd recommend looking at the following:

calvinf
+1 for interesting stuff.
Stephen
A: 

If you are going to be repeatedly inserting HTML (such as through a loop) then I'd use a jQuery templating plug-in. I prefer the one that Microsoft made from John Resig's original design. It gets the job done. Read about it here.

It works like this...

Define a template in the section of your page.

<script id="myTemplate" type="text/html">
  <div>
    <h3>${headerText}</h3>
    <p>${someText}</p>
    <a href="${linkHref}">Click Me</a>
  </div>
</script>

Here some test data:

var testData = 
{
  headerText: 'Hello World',
  someText: 'A long random paragraph about nothing, or Lorem Ipsum.. yadayaya',
  href: 'http://www.stackoverflow.com/'
}

Then you can use the template anytime and as much as you want:

$('#myTemplate').tmpl(testData).appendTo('body');

Results in:

<div>
  <h3>Hello World</h3>
  <p>A long random paragraph about nothing, or Lorem Ipsum.. yadayaya</p>
  <a href="http://www.stackoverflow.com/"&gt;Click Me</a>
</div>

You can create as complex structures as you want. It's very easy to read and maintain.

Enjoy :)

Then you can use this repeatedly.

John Strickler