Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery scroll event - detecting element scrolled into view - poor performance on Chrome

The following code works ok on IE and Firefox, but Chrome hates it (it runs but is really laggy). I am sure it could be made more browser friendly, but how? itemPlaceholder is hundreds of 100x100 floated divs (eg image placeholders). I'm using jquery 1.4.4 and 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;
}

Edit: Replaced append with replaceWith otherwise we get lots of images appended to the same element.

like image 758
Sprintstar Avatar asked Mar 10 '11 23:03

Sprintstar


1 Answers

This runs slowly in chrome because chrome fires the onscroll event continuously as the page is scrolled (IE and firefox only fire onscroll when scrolling stops).

You could improve chrome's performance in this case by queuing up the invocations of ReplaceVisible and only allowing it to be fired once in a given time period. An example of queuing invocations is available here (https://github.com/tilleryj/rio/blob/master/public/javascripts/lib/delayed_task.js)

like image 133
tilleryj Avatar answered Oct 03 '22 06:10

tilleryj