I am using this code to get images to load only if they are visible. However, it seems to be slow with thousands of images, even if they are not rendered.
function getViewportHeight() {
if(window.innerHeight) {
return window.innerHeight;
}
else if(document.body && document.body.offsetHeight) {
return document.body.offsetHeight;
}
else {
return 0;
}
}
function inView(elem, nearThreshold) {
var viewportHeight = getViewportHeight();
var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
var elemTop = elem.offset().top;
var elemHeight = elem.height();
nearThreshold = nearThreshold || 0;
if((scrollTop + viewportHeight + nearThreshold) > (elemTop + elemHeight)) {
return true;
}
return false;
}
function loadVisibleImages() {
jQuery('img[data-src]').each(function() {
if(jQuery(this).is(':visible')) {
if(inView(jQuery(this), 100)) {
this.src = jQuery(this).attr('data-src');
}
}
});
}
jQuery(window).scroll(function() {
loadVisibleImages();
});
I am using this code to render images:
<img src="" data-src="http://placehold.it/400x400" alt="" width="400" height="400">
Everything works, but how can I optimize it?