It's a very common bad practice. We often iterate through array, build HTML contents and keep on concatenating into certain DOM element. Every time you execute the block of code under the loop, you create the HTML markups, discover a div, access the innerHTML of a div, and for += operator you again discover the same div, access its innerHTML and concatenate it before assigning.
function pageLoad()
{
var links = ["microsoft.com", "tanzimsaqib.com", "asp.net"];
$get('divContent').innerHTML = 'The following are my favorite sites:'
for(var i=0; i<links.length; ++i)
$get('divContent').innerHTML += '<a href="http://www.' + links[i] + '">http://www.' + links[i] + '</a><br />';
}
However, as you know accessing DOM element is one the costliest operation in JavaScript. So, it's wise to concatenate all HTML contents in a string and finally assign to the DOM element. That saves a lot of hard work for the browser.
function pageLoad()
{
var links = ["microsoft.com", "tanzimsaqib.com", "asp.net"];
var content = 'The following are my favorite sites:'
for(var i=0; i<links.length; ++i)
content += '<a href="http://www.' + links[i] + '">http://www.' + links[i] + '</a><br />';
$get('divContent').innerHTML = content;
}
No comments:
Post a Comment