0

I have a lot of images (of 5 categories) in my website which make it load slowly.

I set every image with Attribute "data-src" containing its real source, and I update its source attribute with this "data-src" attribute for every image in this categroy (inside a for loop), whenever the relevant category is chosen (clicked).

HTML:

<img loading="lzay" class="post_image" data-src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg" src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg">

JAVASCRIPT:

for(i = 0; i< selection.length; i++){
            let data_src = selection[i].children[2].getAttribute("data-src");;
            selection[i].children[2].src = data_src;
        }

How can I tell when all of the images of a category was loaded to the site? (some code continue to run after the for loop is done, yet not all the images loaded and I wish the rest of the code will fire only after they are loaded to page).

Sascha
  • 4,576
  • 3
  • 13
  • 34
Omer Gafla
  • 46
  • 7
  • Similar https://stackoverflow.com/questions/11003543/how-can-i-make-a-javascript-event-to-trigger-after-all-images-in-an-array-are-lo/11003806#11003806 – Musa Aug 31 '20 at 01:13

1 Answers1

0

Try this. I didn't have much time to come up with it, but it might work. Sorry if it doesn't.

index.html

<img id="img1" src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg"/>
<img id="img2" src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg"/>
<img id="img3" src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg"/>
<script type="text/javascript" src="script.js"></script>

script.js

const img1 = document.getElementById("img1");
const img2 = document.getElementById("img2");
const img3 = document.getElementById("img3");

const imgArray = [
  img1,
  img2,
  img3
]

let imgsLoaded = 0;

for (let i = 0; i < imgArray.length; i++) {
  imgArray[i].onload = function () {
    imgsLoaded++;
  }
  if (imgsLoaded >= imgArray.length) {
    // all images are loaded
  }
}