views:

658

answers:

3

Which is the more efficient way to create the following, hardcoded HTML or Javascript manipulation:

A pre-defined grid, i.e. constant number of rows and columns, with boarders and styles and event handlers. Is it better to have many divs written in HTML.

<div class='tl' id='c00' style='top:0px; left:0px;'>A</div>
<div class='tl' id='c01' style='top:0px; left:20px;'>A</div>
<div class='tl r' id='c02' style='top:0px; left:40px;'>A</div>

Or use a Javascript to generate the divs.

d1 = "<div class='"
d2 = "' id='"
d3 = "' style='"
d4 = "'>"
d5 = "</div>"
sHTML = ""
for (j = 1; j < 5; ++j)
    for (i = 1; i < 5; ++i)
    {
        sClass = "t l ";

        if ((i+1 % 3) = 0)
            sClass = sClass + "r ";

        if ((j+1 % 3) = 0)
            sClass = sClass + "b ";

        sLine = d1 + sClass;
        sLine = sLine + d2 + "c" + n;
        sLine = sLine + d3 + "top:" + (i*20) + "px; left:" + (i*20) + "px;";
        sLine = sLine + d4 + "A";
        sLine = sLine + d5;
        document.writeln(sLine);
    }

The time is takes to create the HTML is not an issue, but as it will be ran locally and probably on a mobile device the pages performance matters more.

Thanks for the help.

+1  A: 

Hard coding it will be faster. The browser needs to parse the html either way. All you are doing by using Javascript is making it very confusing and adding overhead.

Shaun Bowe
also has the benefit of working with javascript disabled
cobbal
agreed.. I didn't even think of that
Shaun Bowe
That's what I thought. Thanks
thing2k
And lots of mobile devices have not yet implemented JavaScript.
Traingamer
A: 

Maintenance will also be significantly easier if you just write the markup out rather than using JavaScript.

If you were going to do it in JS... at least do it using via the HTML DOM

Steve Paulo
A: 

I recommend using significant markup and not using divs for every necessity. In your case an ul list would be appropriate enough

I stated that it would be a grid, to all intent and purpose a table. Therefore a ul wouldn't do it.
thing2k
A list can do anything a div can do. You should choose the correct markup to describe the content most correctly, and the correct CSS to display the content most correctly.
eyelidlessness