优化jQuery悬停代码以更好地执行(更流畅的动画)

时间:2009-10-07 08:44:47

标签: jquery performance optimization hover jquery-animate

最近我花了一些时间阅读jQuery优化技巧,这肯定有助于提高我的脚本的性能。

然而,我在我的网站上有这个特色新闻栏目,鼠标悬停时会将更多信息放到适当的位置,而且这个部分在除Safari之外的任何浏览器中都表现不佳(当时也可能是Chrome。)

我相信,其原因在于它在动画制作之前对每个鼠标悬停/鼠标移动事件进行了一些DOM遍历和计算。

我的问题很简单:有没有办法优化下面的代码,以便动画运行得更顺畅?

$('#featuredSide .featuredBox,#featuredBottom .featuredBox,#archiveVideos .featuredBox').hover(function(){ 
var boxHeight = parseInt($(this).css('height'))-8;
var bottomOrSide = $(this).parents("div[id^='featured']").attr("id")
var captionPos = 76;
var captionHeight = parseInt($(this).find(".videoCaption").css('height'));
var animateTo = boxHeight-captionHeight;

$(".videoCaption", this).stop().animate({top:animateTo + 'px'},{queue:false,duration:160});
}, function() {
$(".videoCaption", this).stop().animate({top:captionPos},{queue:false,duration:100});
});

由于我正在处理的网站尚未发布,我已经uploaded a screenshot of the news section让您了解它的外观。

谢谢!

3 个答案:

答案 0 :(得分:2)

对于初学者,可以执行Common subexpression elimination,例如,而不是调用

$(this)

多次,将该对象存储在变量中并改为使用该变量。

var current = $(this);

另一方面,可以内联单个使用变量。 有些人可能会称之为过早优化,但由于已经说过代码很慢,我认为现在还不成熟。

这里似乎没有使用bottomOrSide变量。

对于选择器,可以用这个替换整个长的东西吗?

$('.featuredBox')

答案 1 :(得分:2)

另一种解决方案是memoize所有计算。

不要直接调用悬停,使用“each”,计算,然后应用“悬停” 因此(我试图尽可能少地改变代码):

$('#featuredSide .featuredBox,#featuredBottom .featuredBox,#archiveVideos .featuredBox').each(function(){ 
  var boxHeight = parseInt($(this).css('height'))-8;
  var bottomOrSide = $(this).parents("div[id^='featured']").attr("id")
  var captionPos = 76;
  var captionHeight = parseInt($(this).find(".videoCaption").css('height'));
  var animateTo = boxHeight-captionHeight;

  var params = {top:animateTo + 'px'};
  var options = {queue:false,duration:160};
  var target = $(".videoCaption", this);

  $(this).hover(function () {
    target.stop().animate(params, options);
  });
}

这个解决方案会让我之前的回答有点没有意义(尽管仍然适用,但它们并不重要)。但请记住要分析。

答案 2 :(得分:1)

你多次做了一些工作,这会伤到你。多难说,但试试这个......

var el = $(this);
var vid = $(".videoCaption", this);
// use el.blar() instead of $(this) and vid.blar() instead of $(".videoCaption", this).blar()

在使用此面板的所有不同位置,您的dom结构看起来也必须不同,因为您的代码似乎必须做一些工作才能找到要使用的dom的相应位。如果可能的话,我建议在所有不同的位置使DOM结构相同,然后在代码中使用该结构。

如果无法做到这一点,请尝试为每个位置编写此功能的唯一版本 - 不理想,但如果它解决了您的性能问题,则可能值得。

相关问题