转自:http://www.jb51.net/article/47219.htm

巧用局部变量可以有效提升javascript性能,下面有个不错的示例,大家可以参考下
 
 

<!-- 优化前 --> 
<script type="text/javascript"> 
function initUI () { 
var bd = document.body, 
links = document.getElementByTagName("a"), 
i=0, 
len=links.length; 
while(i < len){ 
update(links[i++]); 


document.getElementById("go-btn").onclick = function(){ 
start(); 


bd.className = "active"; 

</script> 

该函数引用了三次document,而document是个全局对象。搜索该变量的过程必须遍历整个作用域链接,直到最后在全局变量对象中找到。你可以通过以下方法减少对性能的影响:先将全局变量的引用存储在一个局部变量中,然后使用这个局部变量代替全局变量。 

例如: 

<!-- 优化后 --> 
<script type="text/javascript"> 
function initUI () { 
var doc=document, 
bd = doc.body, 
links = doc.getElementByTagName("a"), 
i=0, 
len=links.length; 
while(i < len){ 
update(links[i++]); 


doc.getElementById("go-btn").onclick = function(){ 
start(); 


bd.className = "active"; 

</script> 
 

相关文章:

  • 2022-12-23
  • 2021-07-24
  • 2021-10-18
  • 2021-07-09
  • 2022-12-23
  • 2021-11-18
  • 2021-09-06
  • 2021-09-09
猜你喜欢
  • 2022-12-23
  • 2022-01-18
  • 2021-08-30
  • 2022-12-23
  • 2022-12-23
  • 2021-08-14
相关资源
相似解决方案