desandro / imagesloaded

:camera: JavaScript is all like "You images done yet or what?"
https://imagesloaded.desandro.com
MIT License
8.88k stars 1.15k forks source link

Run each function after each image is loaded instead of waiting for every image to load and run all functions at once #310

Closed patrulea closed 10 months ago

patrulea commented 10 months ago

imagesLoaded waits until all product’s images are loaded to run productRandomPosition on every product at once.

Though, I’d like to run productRandomPosition on every product as soon as its images load, independent of the rest of the images’ progress.

This is my current code:

products.forEach((product) => {
  // randomize product position when images are loaded
  imagesLoaded(product, () => {
    productRandomPosition(product);
  });
});
patrulea commented 10 months ago

I know this is due to me being a JavaScript novice but I’d be appreciative of any advice.

patrulea commented 10 months ago

I achieved this with no use of the library.

productImages.forEach((image) => {
  if (image.complete) {
    randomPosition(image.parentElement);
  } else {
    image.addEventListener("load", () => {
      randomPosition(image.parentElement);
    });
  }
});