ASP.NET AJAX Best Practices: Careful with DOM element concatenation

本文探讨了在JavaScript中优化DOM元素操作的方法,避免了频繁访问DOM元素造成的性能瓶颈。通过对比两种不同方式来构建和更新页面内容,推荐使用字符串拼接后再一次性赋值给DOM元素的innerHTML属性,以提高网页应用的性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 ASP.NET AJAX Best Practices: Careful with DOM element concatenation

Reference From: http://geekswithblogs.net/Saqib/archive/2008/02/05/asp.net-ajax-best-practices-careful-with-dom-element-concatenation.aspx

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;
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值