I am creating a function which I want to loop through a number of div elements. Waiting for each background-image to load before proceeding with the loop.
My current solution is:
var images = document.getElementsByClassName("previewImg");
for(var i=0; i < images.length; i++){
var imageSrc = images[i].getAttribute("stylesoon");
if(imageSrc != "" || imageSrc != null){
console.log(imageSrc);
var imgToLoad = new Image();
imgToLoad.src = "./".imageSrc;
imgToLoad.onload = function () {
images[i].style.cssText += "background-image: url('"+imageSrc+"');";
}
}
}
The problem is that it is not waiting for the imgToLoad.onload function to complete before proceeding with the loop. I'm not sure how to go about fixing this.
All help appreciated, thanks.
The calls are asynchronous. So you either need to use async/await with a promise or you need to make a queue and pop off an array.
(function() {
const elems = Array.from(document.querySelectorAll('.previewImg[data-stylesoon]'));
function loadNext() {
if (!elems.length) {
console.log('done');
return;
}
const elem = elems.pop();
const url = elem.dataset.stylesoon;
const img = document.createElement("img");
img.onload = function() {
elem.style.backgroundImage = `url('${url}')`;
loadNext();
};
img.onerror = loadNext;
img.src = url;
}
loadNext();
}());
div {
width: 200px;
height: 200px;
}
<div class="previewImg" data-stylesoon="https://placekitten.com/200/200"> </div>
<div class="previewImg" data-stylesoon="https://placekitten.com/200/300"> </div>
<div class="previewImg" data-stylesoon="https://placekitten.com/200/400"> </div>
<div class="previewImg" data-stylesoon="https://placekitten.com/300/500"> </div>