이 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 Tree)를 걷습니다.
또한, 당신은 "비활성화 된 방패"를 동적으로 만들고 있기 때문에 disable
방법, 저장할 수 있습니다
module.data("disabledShield", module.prepend('<div class="disabled_sheild"></div>'));
그리고 당신의 참조를 사용하십시오 enable
Dom Walk를 피하는 방법
module.data("disabledShield").remove();
module.removeClass('disabled');
module.animate({'opacity' : '1.0'}, 300, function(){console.timeEnd('animate');});
(보다 http://docs.jquery.com/internals/jquery.data Doc On의 경우 $.data
)