why is this jQuery .animate call so slow?
Hi All I have a pretty straight forward function
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');
}
The animation its self, the opacity change, is very fast but there is like a delay in calling it. the console.time() is reporting times of 2540MS and greater. I'm thinking it may be because the div#module is being animated along with its children? but this dosent make sense because I have another function "disableModule" which does the same thing in reverse and runs at a reasonable speed.
Here is the disable Module function, considerably more going on but returns times of about 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(){ co开发者_Go百科nsole.timeEnd('animate');});
}
});
});
}
After some arduous troubleshooting i tracked it down to being an issue with the browser detection loop in the disable method:
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');});
}
});
Commenting this block out brought everything up to speed. I almost pulled my hair out after trying to optimize everything else.
Have you tried simply re-ording them?
module.find('.disabled_sheild').remove();
module.removeClass('disabled');
module.animate({'opacity' : '1.0'}, 300, function(){console.timeEnd('animate');});
Animation happens asynchronously and the find
and remove
methods could be consuming resources (especially since find
walks the DOM tree) that could otherwise be used to for the animation.
Also, since you are dynamically creating the "disabled shield" in the disable
method, you could save it off
module.data("disabledShield", module.prepend('<div class="disabled_sheild"></div>'));
and just use that reference in your enable
method to avoid the DOM walk
module.data("disabledShield").remove();
module.removeClass('disabled');
module.animate({'opacity' : '1.0'}, 300, function(){console.timeEnd('animate');});
(See http://docs.jquery.com/Internals/jQuery.data for doc on $.data
)
精彩评论