Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!