skip to Main Content

my code:

  const checkImagetest = images =>
    new Promise(resolve => {
       images.forEach(function (el) {
         let src = el.getAttribute("src");  console.log("src: ",src) // gives->src/hero.jpg src/hero1.jpg?v=1-0
         const img = new Image();
         img.onload = () => resolve(true);
         img.onerror = () => resolve(false);
         img.src =src;
       });
  });


const loadImgtest = (...images) => Promise.all(images.map(checkImagetest));

loadImgtest(document.querySelectorAll('[data-lg-loadImg]')).then(results => {
  console.log("results: ",results);    //gives->Array [ true ] (only the last src-value)
    if (results.every(res => res))     //The every() method returns true if the function returns true for all elements. The every() method returns false if the function returns false for one element.
        console.log('all [data-lg-loadImg]-images loaded successfully');
    else
        console.log('some [data-lg-loadImg]-images failed to load, all finished loading');
});

this do not work propper.
The .then(results => { … gives only the last promise state back.
In the example it should has to be a array with lenght 2.
Whats wrong?

3

Answers


  1. Chosen as BEST ANSWER

    I came up with this solution:

        const preloadImages = (selector = '[data-lg-loadImg]') => {
        return Promise.all(Array.from(document.querySelectorAll(selector)).map(el => {
            const img = new Image();
                  img.src = el.getAttribute("src");
            if (img.complete)
                return Promise.resolve(img.naturalHeight !== 0);
            return new Promise(resolve => {
                img.addEventListener('load', () => resolve(true));
                img.addEventListener('error', () => resolve(false));
            });
        }))
    };
    
    preloadImages().then(results => {
        if (results.every(res => res))     //geht nur mit true/false   The every() method returns true if the function returns true for all elements. The every() method returns false if the function returns false for one element.
            console.log('---------------all [data-lg-loadImg]-images loaded successfully');
        else
            console.log('----------------some [data-lg-loadImg]-images failed to load, all finished loading');
    });
    

    I this the way it works?


  2. You had the right basic idea, but you are not making a promise for each image. You are looping multiple times. The map should be looping over the images and you should not be looping over the images in the promise.

    function checkImg = el => 
      new Promise(resolve => {
        const src = el.getAttribute("src");
        const img = new Image();
        img.onload = () => resolve(true);
        img.onerror = () => resolve(false);
        img.src =src;
      });
    
    const images = document.querySelectorAll(...);
    
    const promises = Array.from(images).map(checkImg);
    
    Promise.all(promises)
      .then(results => {
        console.log(results);
      });
    
    Login or Signup to reply.
  3. But this does not make any sense if the image has src since that would already be requested by the browser

    Don’t you mean something like this?

    const checkImg = el => new Promise((resolve, reject) => {
      if (!el || !el.dataset || !el.dataset.src) {
        return reject(new Error("Invalid element or missing data-src attribute"));
      }
      const img = new Image();
      img.onload = () => {
        el.src = el.dataset.src; // Update the src attribute on load
        resolve(true);
      };
      img.onerror = () => resolve(false);
      img.src = el.dataset.src; // Load the image
    });
    
    window.addEventListener("DOMContentLoaded", () => {
      const images = [...document.querySelectorAll("[data-src]")];
    
      if (images.length === 0) {
        console.log("No elements with [data-src] found.");
      } else {
        const promises = images.map(checkImg);
    
        Promise.all(promises)
          .then(results => {
            console.log(results);
          })
          .catch(error => {
            console.log(error);
          });
      }
    });
    <img src="https://dummyimage.com/200x200/000/fff.png&text=dummy" data-src="https://dummyimage.com/200x200/000/f00.png&text=Actual1">
    <img src="https://dummyimage.com/200x200/000/fff.png&text=dummy" data-src="https://dummyimage.com/200x200/000/ff1.png&text=Actual2">
    <img src="https://dummyimage.com/200x200/000/fff.png&text=dummy" data-src="https://dummyimage.com/200x200/000/f0a.png&text=Actual3">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search