2009-11-26 74 views
1

大家好我有一个非常简单的功能为什么这个jQuery .animate调用这么慢?

enableModule : function(moduleName){ 
     var module = $('div#'+moduleName); 
     console.log('enabling '+moduleName); 
     console.time('animate'); 
     module.animate({'opacity' : '1.0'}, 300, function(){console.timeEnd('animate');}); 
     module.find('.disabled_sheild').remove(); 
     module.removeClass('disabled'); 
     console.log('end of enable Module'); 
    } 

动画自身,不透明度的变化,是非常快的,但没有像在调用它的延迟。 console.time()报告的时间为2540MS或更长。我想这可能是因为div#模块正在与其孩子一起动画?但这种剂量是有道理的,因为我有另一个功能“disableModule”,它在相反的方向做同样的事情,并以合理的速度运行。

这里是禁止模块功能,相当多的事情,但返回的约242ms

disableModule : function(moduleName){ 
     $('div#'+moduleName+', div.'+moduleName).each(function(){ 
     var module = $(this); 
     module.prepend('<div class="disabled_sheild"></div>'); 
     var sheild = module.find('.disabled_sheild'); 
     sheild.css({'position' : 'absolute', 'z-index' : '200'}); 
     sheild.width(module.width()); 
     sheild.height(module.height()); 
     jQuery.each(jQuery.browser, function(i) { 
      if($.browser.msie){ 
       //module.css("display","none"); 
       //if using ie give sheild a transparent background layout 
      }else{ 
       console.time('animate'); 
       module.animate({'opacity' : '0.5'}, function(){ console.timeEnd('animate');}); 
      } 
      }); 
     }); 
    } 

回答

3

一些艰苦后故障排除我跟踪它到是在禁用方法的浏览器检测回路的问题:

jQuery.each(jQuery.browser, function(i) { 
     if($.browser.msie){ 
     //module.css("display","none"); 
     //if using ie give sheild a transparent background layout 
     }else{ 
     console.time('animate'); 
     module.animate({opacity : 0.5}, 200, function(){console.timeEnd('animate');}); 
     } 
    }); 

谈到这一块带来了一切加快速度。在尝试优化其他一切后,我差点拉出头发。

1

次你试过简单地重新奥尔丁呢?

module.find('.disabled_sheild').remove(); 
module.removeClass('disabled'); 
module.animate({'opacity' : '1.0'}, 300, function(){console.timeEnd('animate');}); 

动画异步发生和findremove方法可以消耗资源(尤其是因为find走DOM树)原本可以用于为动画。

而且,因为你是动态创建的disable方法“已禁用盾”,你可以将它保存关闭

module.data("disabledShield", module.prepend('<div class="disabled_sheild"></div>')); 

,只是使用引用您的enable方法,以避免DOM走

module.data("disabledShield").remove(); 
module.removeClass('disabled'); 
module.animate({'opacity' : '1.0'}, 300, function(){console.timeEnd('animate');}); 

(见http://docs.jquery.com/Internals/jQuery.data的文档上$.data