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

169
Vistas
Only append document if image is valid using jquery

I have an array of image urls that I need to add to a document (shown below). Some of the urls do not contain images. How do I check this?

picUrls = ["https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/048.jpg","https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18166-shivling-whatsapp-image-and-dp.jpg","http://www.fakeurl.io/fakeimage1.jpeg","https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18416-navratri-image-for-whatsapp-and-facebook.jpg"]

I am using jquery and have tried the .load & .error

for(let i = 0; i < picUrls.length; i++) {
    const picUrl = picUrls[i];

    //create image to preload:
    var imgPreload = new Image();
    $(imgPreload).attr({
      src: picUrl
    });
    
    //check if the image is already loaded (cached):
    if (imgPreload.complete || imgPreload.readyState === 4) {
    
      //image loaded:
      //your code here to insert image into page
      $('#content-container').append(imgPreload);
    
    } else {
      //go fetch the image:
      $(imgPreload).load(function (response, status, xhr) {
        if (status == 'error') {
    
          //image could not be loaded:
          console.log('error');
        } else {
    
          //image loaded:
          //your code here to insert image into page
          $('#content-container').append(imgPreload);
    
        }
      });
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can create a helper function that returns a promise whether an image is a valid image or not

      const picUrls = [
        'https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/048.jpg',
        'https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18166-shivling-whatsapp-image-and-dp.jpg',
        'http://www.fakeurl.io/fakeimage1.jpeg',
        'https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18416-navratri-image-for-whatsapp-and-facebook.jpg',
      ];

      const getOnlyValidImage = src =>
        new Promise((resolve, reject) => {
          const img = new Image();
          img.src = src;
          img.onload = () => resolve(img);
          img.onerror = () => resolve(null);
        });

      const preloadImages = async () => {
        for (let i = 0; i < picUrls.length; i++) {
          const picUrl = picUrls[i];
          const image = await getOnlyValidImage(picUrl)
          if (image) {
            $('#content-container').append(image);
          }
        }
      };

      preloadImages();
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