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

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

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 Denunciar

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 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