I have this code for lazy load images:
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).on('scroll', function() {
$('.imgli').each(function(){
if ($(this).isInViewport()) {
$(this).attr("src", $(this).attr("data-src")).removeAttr('data-src');
}
});
});
It works with about 700 images, but I'm interesting - what about 20.000 images (max)?
Is there any way to check this, without really loading 20.000 images, because I don't have so much of them, for now.
Each image is about 100kb max.
First of all you can always copy your existing images to make it 20.000 though it is a little bit pointless.
Secondly you can force reload the picture every time it appears in a viewport.
$(window).on('scroll', function() {
$('.imgli').each(function(){
if ($(this).isInViewport()) {
$(this).attr("src", $(this).attr("data-src") + "?" + $.now());
}
});
});
So you can just scroll the page and see how the pictures are getting loaded every time they appear in a viewport.
Additionally eavoid using $(this)
more than it's necessary.
A better way is to save it to a variable. That way you save memory.
$(window).on('scroll', function() {
$('.imgli').each(function() {
var image = $(this);
if (image.isInViewport()) {
image.attr("src", image.attr("data-src") + "?" + $.now());
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.