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

204
Views
How to know when image preloading is done with javascript?

Per this extremely popular question, preloading images with javascript is as easy as:

function preloadImage(url) {
  var img=new Image();
  img.src=url;
}

But what I'd like to know is how can you know when that's done? I could just do a small setTimeout and assume it will be done after some small delay, but with varying connection speeds and especially for large images or large numbers of images this is unreliable.

Is there any way to actually know for sure when the loading is done?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Image elements have two events that you can subscribe to to know that the image has loaded: onload and onerror:

function preloadImage(url, doneCallback) {
  var img=new Image();
  img.src=url;

  img.onload = () => {
    doneCallback();
  }

  img.onerror = () => {
    doneCallback(new Error('Failed to load image ' + url));
  }
}

preloadImage(url, (err) => {
  if (err) {
    console.log(err.message);
  }
  else {
    console.log('Preloading DONE!');
    // do what you want after preloading here!
  }
}

Or if you prefer Promises (so you can use async/await etc.):

function preloadImage(url) {
  var img=new Image();
  img.src=url;

  return new Promise((done, fail) => {
    img.onload = () => {
      done();
    }

    img.onerror = () => {
      fail(new Error('Failed to load image ' + url));
    }
  });
}

async function main () {
    console.log('preloading image!');

    await preloadImage(url);

    console.log('done preloading image!');
}

main().catch((err) => {
  console.log(err.message);
});
about 4 years ago · Juan Pablo Isaza Report

0

Just found the answer to my own question on the MDN docs for the Image class. There is a complete boolean attribute that tells you whether it's done.

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!