lazy loading images are loading too slowly

images folder contains about 14000 jpg images.

I want to load them using loading = 'lazy' but there is a performance problem on a client side (Chrome).

Each scroll firstly shows empty rectangles and then the images are loading, but very slowly.

On youtube home page I'm scrolling fluently, i.e. without waiting for images, and as I can see - there is no limit to scroll down.

How to solve this?

$arr = glob("../images/*.jpg");
$ht = '';
foreach($arr as $el){
    $ht .= "<img class='bimg' src = '" . $el . "' width = 151.11' height = '86.73' alt = 'img' loading = 'lazy'>\n";
echo $ht;

2 answers

  • answered 2019-11-20 03:22 domdambrogia

    Do you really need to show 14000 images? Is a user realistically going to scroll through 14000 images? Will they even scroll through 500? I'm unfamiliar with the lazy attribute, but I assume the more you have the more work the browser has to do which is why you're seeing a performance issues. What was the last site you visited with even a <ul> of 14000 items in a row? Even large <table> elements are paginated.

    I would guess you could render less images at once (even 100 is a lot to lazy load at once depending on the size) and once the user gets to the 50 mark, make a request for 100 more, etc. Paginate your requests.

    The other thing you could look at would be the common data-lazy= You can read more about that here. Even if you don't use a framework there are plenty of other resource on how to load an image based on the window scroll event.

    Here is a fairly simple answer:

    My 2 cents is that you don't need 14k images at once, it seems unrealistic to use that many images. Adjust your logic to use what you need, when you need it.

  • answered 2019-11-20 03:38 smzapp

    14000 in one page request? I can't even imagine for 1k of images to be loaded in a browser, how much more if it is already 14k.

    From your code:

    foreach($arr as $el){
       $ht .= "<img class='bimg' src = '" . $el . "' width = 151.11' height = '86.73' alt = 'img' loading = 'lazy'>\n";

    I have few suggestions:

    • You're loading all images src='".$el."' in a browser. Usually, lazyload does not fetch the image in src attribute. It sometimes stores the location via data attribute and then the lazyload plugin will fetch it dynamically.

    • Check your network tab to check the performance of your page.

    • For 14k of images, I would suggest that you fetch data by batch. Example, load 100 out of 1000, and so on. You might do it via ajax.