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

145
Views
how to check if a image will load or not in JS

I am making a news website with news API for practice and sometimes some images do not load. So how can I set a logical condition like "use this image if this does not load".

Thanks

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

0

You can do that like this...
Replace the invalid_link and https://placeimg.com/200/300/animals with your links.

<img src="invalid_link" onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';">

about 4 years ago · Juan Pablo Isaza Report

0

It's not clear how you're handling the images - are they hardcoded in the HTML, are they in an array?

This example uses a Promise-based method to replace all bad images with dummy images.

An array of image objects (name, src), is mapped over. For each iteration (for each object) it calls checkIfImageExists with the src, and based on what the function returns (either true or false) returns either the original object (true) or a new object with the dummy image as the src.

When you run the snippet you will see that badImage (2nd object) has had the src replaced with the dummy image URI.

function checkIfImageExists(src) {

  return new Promise(res => {

    const img = new Image();

    img.src = src;

    if (img.complete) {
      res(true);
    } else {

      img.onload = () => {
        res(true);
      };

      img.onerror = () => {
        res(false);
      };

    }
  });

}

const dummy = 'https://dummyimage.com/48x48/633a63/000000.png&text=n/a';

const imgs = [
  { name: 'flower', src: 'https://images.unsplash.com/photo-1649922694096-35448dfd411f' },
  { name: 'badImage', src: 'https://images.unsplash.com/photo-1649922694096-35448dfd411eeeddddd'  },
  { name: 'sign', src: 'https://images.unsplash.com/photo-1649928210166-52c1b1d8279e' }
];

function filterImages(data) {
  return data.map(async obj => {
    const exists = await checkIfImageExists(obj.src);
    if (exists) return obj;
    return { ...obj, src: dummy };
  });
}

async function main() {
  console.log('Waiting for the image-checking to complete...');
  const filtered = await Promise.all(filterImages(imgs));
  console.log(filtered);
}

main();

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!