Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

160
Visualizações
Wait for image to load before proceeding with for loop

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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">&nbsp;</div>
<div class="previewImg" data-stylesoon="https://placekitten.com/200/300">&nbsp;</div>
<div class="previewImg" data-stylesoon="https://placekitten.com/200/400">&nbsp;</div>
<div class="previewImg" data-stylesoon="https://placekitten.com/300/500">&nbsp;</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda