Dynamically Generate HTML Element Using Strings and Arrays

Thursday, June 26, 2008

Eventhough DOM is maybe the most powerfull technique to manipulate a page's content, sometimes we can get performance benefits by not using it and use core javascript objects instead. In the following example I'll use strings and arrays to generate a table. I'll show both way for comparison. Remember, minimizing your code's use of OM objects can always increase your page's performance. Here's an example of a DOM scripting technique:

function createTable(numRows, numCols) {
    var idRow = 0, idCol = 0;
    var oTable = document.createElement("TABLE");
    var oTBody = document.createElement("TBODY");
    var oTRow = null;
    var oTCol = null;

    for (idRow; idRow < numRows; idRow++) {
        oTRow = document.createElement("TR");
        oTRow.style.border="solid 1px blue";
        for (idCol = 0; idCol < numCols; idCol++) {
            oTCol = document.createElement("TD");
            oTCol.innerText = "("+idRow + ", " + idCol+")";
            oTRow.appendChild(oTCol);
        };
        oTBody.appendChild(oTRow);
    };
    oTable.appendChild(oTBody);
    document.body.appendChild(oTable);
};
Call the script on your page using onload="createTable(5, 5)" for example. And here's an example using the strings and arrays:
function createTable(numRows, numCols) {
    var idRow = 0, idCol = 0;
    var buffer = new Array();
    var bufferCount = 0;
    buffer[bufferCount++] = "<table><tbody>";

    for (idRow; idRow < numRows; idRow++) {
        buffer[bufferCount++] = "<tr>";
        for (idCol = 0; idCol < numCols; idCol++) {
            buffer[bufferCount++] = "<td>";
            buffer[bufferCount++] = "("+idRow;
            buffer[bufferCount++] = ", ";
            buffer[bufferCount++] = idCol+")";
            buffer[bufferCount++] = "</td>";
        };

        buffer[bufferCount++] = "</tr>";
    };

    buffer[bufferCount++] = "</tbody></table>";
    document.body.innerHTML += buffer.join("");
};
The outputs of both code is the same, but the second is faster than the first. It proves that manipulating page dynamically is faster using core javascript code than using the DOM API. In the second method, we used buffer array to store the HTML strings. This method avoids using more CPU cycles to concatenate new element separately like in the first method. In short, the second method is faster because it changes the element in one complete string while the first method does it per element. Hope this helps.

0 comments: