Don’t hesitate to contact us if you have any feedback.

Javascript – Check if images are fully loaded

Web developers often face the challenge of executing scripts that depend on the complete loading of all images on a page. This JavaScript code snippet provides a reliable way to run a script only after verifying that every image has finished loading, enhancing the user experience by ensuring that visual content is ready before initiating any dependent processes.

The Code

Promise.all(
  Array.from(document.images)
    .filter((img) => !img.complete)
    .map(
      (img) =>
        new Promise((resolve) => {
          img.onload = img.onerror = resolve;
        })
    )
).then(() => {
  console.log('Images are fully loaded');
});

How It Operates

The code snippet uses Promise.all to handle a collection of promises, each corresponding to the load event of an image:

  1. document.images is used to create an array of all image elements on the page.
  2. The .filter() method excludes images that have already completed loading.
  3. The .map() method converts each remaining image into a promise that resolves when the image’s onload or onerror event fires.
  4. Promise.all waits for all these promises to resolve, which occurs when all images have finished loading or if an error occurs during loading.

When to Use

This approach is particularly useful when you need to:

  • Initialize a photo gallery only after all images are available.
  • Calculate the dimensions of content that includes images.
  • Ensure that all visual assets are in place before starting animations.

Advantages

  • Reliability: Scripts will run only after the necessary visual content is fully loaded.
  • Performance: Prevents premature script execution, which can lead to errors or incomplete content rendering.
  • User Experience: Enhances the perception of a seamless and responsive page load.

By implementing this code, you can synchronize your scripts with the complete loading of images, ensuring that any subsequent actions take place at the appropriate time.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *