Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda