Consider the following example. It's a simple HTML unordered list representing folders and files:
- Folder 0
- File 0
- File 1
- File 2
- Folder 1
- File 0
- File 1
- File 2
<ul id="folderList">
<li>Folder 0
<ul>
<li>File 0</li>
<li>File 1</li>
<li>File 2</li>
</ul>
</li>
<li>Folder 1
<ul>
<li>File 0</li>
<li>File 1</li>
<li>File 2</li>
</ul>
</li>
</ul>
Now, let's generate the same output using JavaScript:
var h = [];
for(var i=0;i<=1;i++)
{
h.push("<li>Folder ");
h.push(i);
h.push("<ul>");
for(var k=0;k<=2;k++)
{
h.push("<li>File ");
h.push(k);
h.push("</li>");
}
h.push("</ul></li>");
}
document.getElementById("folderList").innerHTML = h.join("");
You may think this script looks ugly, but it's actually the fastest way to manipulate the DOM in JavaScript. You create an array of strings and add chunks of HTML to it. Then you join (or concatenate) the array to form one big string and set the parent element's innerHTML property to it.
To evaluate both methods, I created two HTML files, both containing a huge list of 500 folders x 500 files (250.000 items in total). The first file is using static HTML and the second file is using a JavaScript loop to generate the items dynamically. For the record, the static HTML file had an impressive size of 16 MB.
I then loaded each page locally with Firefox and used the YSlow add-on to measure page loading time. If you want to test this for yourself, I uploaded both the plain HTML and the JavaScript benchmark page.
The result (lower is better):
- Plain HTML: 17 seconds
- JavaScript: 9 seconds
A downside of the string array method is that it produces ugly code, with a template engine you'll have a much prettier syntax. Another downside with JavaScript templating is that it complicates machine readability. For example, automated parsers like search engines or screen readers may have problems with it. Only use script generated data for non-SEO relevant content.
No comments:
Post a Comment