requestAnimationFrame在Firefox中占用CPU

时间:2012-07-12 19:24:50

标签: javascript firefox coffeescript sticky requestanimationframe

所以,我正在使用Paul Irish的requestAnimationFrame在页面上制作侧边栏“粘性”。我发现至少在webkit浏览器中,这比其他解决方案(如Waypoints)带来了巨大的性能提升。但是,我在Firefox上注意到,当我开始滚动页面时,CPU会通过屋顶,因此页面速度非常慢。我实现了这个错误,还是我需要为Firefox使用另一种方法?

    (function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

window.widget_is_sticky = false;
window.widget_is_locked = false;

$(function(){

  (function animloop() {
    requestAnimationFrame(animloop);
    if (adjust_networth) {
      if (self.pageYOffset) {
        yScroll = self.pageYOffset;
      } else if (document.documentElement && document.documentElement.scrollTop) {
        yScroll = document.documentElement.scrollTop;
      } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
      }
      update_networth_position(yScroll);
    }
  })();
});

// Separate file written in CoffeeScript
window.update_networth_position = ( offset ) ->
  if offset >= 259
    if !window.widget_is_sticky
      window.widget_is_sticky = true
      $('.widgets').addClass 'sticky'
    else if !window.widget_is_locked and widget_is_at_boundary(offset)
      window.widget_is_locked = true
      $('.widgets').addClass 'locked'
    else if !widget_is_at_boundary(offset) and window.widget_is_locked
      window.widget_is_locked = false
      $('.widgets').removeClass 'locked'
  else
    return false if !window.widget_is_sticky

    $('.widgets').removeClass 'sticky'
    window.widget_is_sticky = false


widget_is_at_boundary = ( offset ) ->
  offset = offset - $('section.top-section').outerHeight(true)
  maximum_height = $('section.main-content div.content:first-child').outerHeight(true)
  widget_height  = $('section.main-content .widgets').outerHeight(true)

  if (offset + widget_height) > maximum_height
    return true
  else
    return false

非常感谢任何帮助!对于如何处理这个问题,我也对完全不同的解决方案持开放态度(但Waypoints的表现不够好)。

1 个答案:

答案 0 :(得分:0)

对此抱歉,误报。事实证明,性能打击来自我正在使用的后台css技术。 requestAnimationFrame这次是安全的:)