thing2k
thing2k

Reputation: 608

Table/Grid Layout - hardcoded HTML vs generated by Javascript

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.

Upvotes: 0

Views: 1518

Answers (3)

Gianmaria Vitale
Gianmaria Vitale

Reputation:

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

Upvotes: 0

Steve Paulo
Steve Paulo

Reputation: 18154

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

Upvotes: 0

Shaun Bowe
Shaun Bowe

Reputation: 10008

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.

Upvotes: 1

Related Questions