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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With