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
I came up with this solution:
I this the way it works?
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.
But this does not make any sense if the image has
src
since that would already be requested by the browserDon’t you mean something like this?