jQuery滚动事件 - 检测元素滚动到视图中 - Chrome上的性能不佳

Spr*_*tar 6 javascript jquery dom scroll google-chrome

以下代码在IE和Firefox上运行正常,但Chrome讨厌它(它运行但是非常滞后).我相信它可以使浏览器友好,但如何?itemPlaceholder是数百个100x100浮动div(例如图像占位符).我正在使用jquery 1.4.4和Chrome v10.0.648.127.

$(function () {

   ReplaceVisible();
   $(this).scroll(function () {
      ReplaceVisible();
   });
});

function ReplaceVisible() {
    $('.itemPlaceholder').each(function (index) {
        if (HasBeenScrolledTo(this)) {
            $itemPlaceholder = $(this);

            $itemPlaceholder.replaceWith('<img src="bicycle.jpg" />');
        }
        else {
            return false;
        }
    });
}

function HasBeenScrolledTo(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;

    return elemTop < docViewBottom;
}
Run Code Online (Sandbox Code Playgroud)

编辑:替换appendreplaceWith否则我们会将大量图像附加到同一元素.

til*_*ryj 5

这在chrome中运行缓慢,因为chrome会在页面滚动时连续触发onscroll事件(IE和firefox仅在滚动停止时触发onscroll).

在这种情况下,您可以通过排队ReplaceVisible的调用来提高chrome的性能,并且只允许在给定时间段内触发一次.这里有一个排队调用的例子(https://github.com/tilleryj/rio/blob/master/public/javascripts/lib/delayed_task.js)

  • 直接来自马的嘴:http://ejohn.org/blog/learning-from-twitter/ (2认同)