Hack 80. Use Strings and Arrays to Dynamically Generate HTML


Speed up the dynamic writing of HTML tables and CSS styles.

DOM programming in the latest versions of modern browsers, despite their compatibility differences, is a powerful technique for generating new content in the client. However, the large client-side programs that dynamically write HTML tables, for instance, from persistently stored data, can gain performance benefits by using core or "raw" JavaScript objects instead of the DOM. This hack uses JavaScript strings and arrays to dynamically generate an HTML table for a browser view; it shows a code sample for this approach and the DOM-based technique as a basis for comparison.

The hack also describes a technique for dynamically setting Cascading Style Sheet (CSS) styles that helps increase the performance of JavaScript code that alters the appearance of an HTML element.

Writing a Table

In many situations, such as dynamically writing an HTML table, minimizing your code's use of the web page's DOM objects can increase your program's performance. Following are two different examples of building an HTML table. The first one emphasizes DOM scripting, and the second uses JavaScript arrays and strings. The first approach looks like this:

function buildTable(nRows, nCols) {     var idx = 0, idx2 = 0;     var oTable = document.createElement("TABLE");     var oTBody = document.createElement("TBODY");     var oTRow = null;     var oTCol = null;     for (idx; idx < nRows; idx++) {         oTRow = document.createElement("TR");         for (idx2 = 0; idx2 < nCols; idx2++) {             oTCol = document.createElement("TD");             oTCol.innerText = nRow + ", " + nCol;             oTCol.style.fontSize = "12px";             oTCol.style.fontWeight = 700;             oTCol.style.fontFamily = "tahoma";             oTRow.appendChild(oTCol);         };         oTBody.appendChild(oTRow);     };     oTable.appendChild(oTBody);     document.body.appendChild(oTable); };

And here's the second approach:

function buildTable(nRows, nCols) {     var idx = 0, idx2 = 0;     var bufferHTML = new Array(  );     var bufferCount = 0;     bufferHTML[bufferCount++] = "<table><tbody>";     for (idx; idx < nRows; idx++) {         bufferHTML[bufferCount++] = "<tr>";         for (idx2 = 0; idx2 < nCols; idx2++) {             bufferHTML[bufferCount++] =                      "<td style='font-size:12px;font-family:"+                     "tahoma;font-weight:700'>";             bufferHTML[bufferCount++] = nRow;             bufferHTML[bufferCount++] = ", ";             bufferHTML[bufferCount++] = nCol;             bufferHTML[bufferCount++] = "</td>";         };         bufferHTML[bufferCount++] = "</tr>";     };     bufferHTML[bufferCount++] = "</tbody></table>";     document.body.innerHTML += bufferHTML.join(""); };

Using arrays and strings to write HTML dynamically into the page is, relatively, faster than using the DOM APIs.

Running a test program that times the two code pieces indicates that the DOM table-writing example took roughly twice as many milliseconds to run as the second code sample (about 1000 ms, compared with 500).


Performance Matters

In the second code sample, the code accesses the DOM with one code line, rather than with several method calls as in the first example:

document.body.innerHTML += bufferHTML.join("");

In addition, the code uses an Array object to store all the various pieces of the HTML string. This strategy avoids using unnecessary CPU cycles to continually concatenate new pieces of text to the string (similar to a java.lang.StringBuffer object in the Java language).

There are times when using only strings to build HTML is not an option; the code has to make a DOM call to create or change the content of a particular element. The following code samples illustrate two more examples of how this can be done.

Here is one example that changes a web page element dynamically. The function changes the appearance of an element by accessing the element's style property, thus altering its visual aspects (such as the size and color of the font):

function changeElementContents(sID) {     var oEl = document.getElementById(sID);     oEl.style.fontWeight = 700;     oEl.style.fontFace = "Arial";     oEl.style.fontSize = "20px";     oEl.style.backgroundColor = "red";     oEl.style.color = "white";     oEl.innerHTML = "Hello World, Contents Changed";     oEl.noWrap = true; };

The second version of this task minimizes the number of times the code accesses DOM APIs by reducing the number of .style references:

function changeElementContents(sID) {     var oEl = document.getElementById(sID);     with (oEl) {         style.cssText=                  "font-weight:700;font-face:Arial;font-size:20px;"+                 "background-color:red;color:white;";         innerHTML = "Hello World, Contents Changed";         noWrap = true;     }; };

In addition, the style.cssText property allows the code to change all CSS style properties in one shot, rather than altering them piece by piece. Similar optimization strategies may improve the performance of large programs that include a lot of DOM scripting.

Even though a number of tutorials and blogs do not recommend using with, the with statement can provide a small increase in performance if used correctly. However, developers should be wary about putting any other code inside a with block unless it strictly deals with setting the values of existing object properties.


Sean Snider




Ajax Hacks
Ajax Hacks: Tips & Tools for Creating Responsive Web Sites
ISBN: 0596101694
EAN: 2147483647
Year: 2006
Pages: 138

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net