このjQuery .animate呼び出しがなぜこんなに遅いのですか?
-
05-07-2019 - |
質問
こんにちは、私はかなり単純な機能を持っています
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#moduleがその子と一緒にアニメーション化されているからかもしれませんか?しかし、別の関数「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');});
}
});
});
}
解決
いくつかの骨の折れるトラブルシューティングの後、無効化メソッドでのブラウザー検出ループの問題であることを突き止めました:
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');});
}
});
このブロックをコメントアウトすると、すべてが高速化されました。他のすべてを最適化しようとした後、私はほとんど髪を引き出しました。
他のヒント
単純に再調整してみましたか?
module.find('.disabled_sheild').remove();
module.removeClass('disabled');
module.animate({'opacity' : '1.0'}, 300, function(){console.timeEnd('animate');});
アニメーションは非同期的に発生し、 find
および remove
メソッドはリソースを消費する可能性があります(特に 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
のドキュメント用)
所属していません StackOverflow