> From: Andrea Ercolino
> 
> I have got an array of 50 urls templates, and want to make a 
> proper url out of each one, adding also a special click, and 
> then append all these urls to a div in a specific position. 
> All this should be done many times in a page, "many" could be 
> 50, just to say something that could be possible, but it's 
> really an unpredictable number of times. (well, less than a 
> 100 is a good guess)
> 
> I think the problem lies in the dom creation. 
> Each link is inside 4 nested divs, so this could mean 80 
> bytes each (adding structure and data).
> At only 3 divs ( x 50 = 150 appends ) I'm experimenting a 
> delay of a couple of seconds for reloading the page, and for 
> this test the page has no content other than those divs!

Yeah, all that DOM creation will take a while - especially if you use a
convenience plugin like mine.

I get much better performance across browsers with [].join('') and
innerHTML.

Here's a design pattern I use all the time. I threw in some arbitrary divs
and spans to show how the nesting works out.

    // Return HTML rendering for an array of strings
    function renderAll( array ) {
        var inner = [];
        for( var i = 0, len = array.length;  i < len;  i++ ) {
            inner[inner.length] = renderOne( array[i], i );
        }
        
        return [
            '<div id="wrap1">',
                '<div id="wrap2">',
                    inner.join(''),
                '</div>',
            '</div>'
        ].join('');
    }

    // Return HTML rendering for a string item
    function renderOne( item, i ) {
        return [
            '<div id="myitem', i, '">',
                '<span class="myitem">',
                    item,
                '<span>',
            '</div>'
        ].join('');
    }

A test call could be:

$('#testdiv').html( renderAll( [ 'one', 'two', 'three' ] ) );

This same basic pattern works for tables, or anything where you have nested
and repeated elements. It works in just about any browser - even very old
ones, thanks to the use of inner[inner.length] instead of inner.push(). And
it's very fast - much faster than the same DOM operations.

Obviously you could replace the [].join('') with ordinary string
concatenation, but the array join is faster on most browsers.

The one big drawback is that you don't automatically get references to the
objects you're creating. With DOM creation, you can save references to your
objects, making it very fast to get to those objects later. To make up for
this, you can assign unique IDs in the HTML code as the example does.

Obviously you could extend this all sorts of ways. In my actual code, the
"item" is usually an object and not a string, and the renderOne function
builds up HTML from that object's properties.

-Mike


_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/

Reply via email to