Knowing if an image exists or not correctly charged

2

How would you know when an image exists or is loaded in the browser with javascript and Jquery , would be an example like this;

This to load an alternative image in case the image does not exist, something like IMAGE NOT FOUND .

    
asked by Albert Hidalgo 09.10.2018 в 16:21
source

3 answers

4

I have managed to solve this in the following way:

A simple script

$(document).ready(function(){
    /**
     * Determinar si una imagen existe por la propiedad naturalHeight
     * la cual sera diferente de 0 si esta existe
     **/
    $('img').each(function(){
        if($(this)[0].naturalHeight == 0){
             $(this).attr('src','images/image_not_found.jpg');
        }
    });
});

I managed to find this solution through the property naturalHeight which must be different from 0 if the image exists, no matter how small the image must have a height.

Maybe it's not the best way but if you have a "big" project many times javascript is a solution.

    
answered by 09.10.2018 / 16:21
source
4

The images ( <img> tags), when you work with the DOM, are objects of the type HTMLImageElement . This element can make use of the "onerror" and "onload" events:

const imgs=Array.from(document.querySelectorAll('img'));
imgs.forEach(i => i.addEventListener('error',event => {
  console.log('Falló la carga de', event.target.src);
  })
);
<img src="http://via.placeholder.com/350x150"/>
<img src="http://falla.noexisto.doh"/>

The problem here is that the javascript that adds the listeners can be loaded later than the images, so these errors would not be detected, but it is a useful method when you are injecting images into the DOM after loading the page .

    
answered by 09.10.2018 в 16:46
0

I find your solution very interesting. Another way to do it would be to take advantage of the onerror event. Launched on an image would fire when the link returned a route error.

JS

function reemplaza_imagen(imagen) {
    imagen.onerror = "";
    imagen.src = "/imagenes/imagen_error_carga.png";
    return true;
}

HTML

<img src="image.png" onerror="reemplaza_imagen(this);"/>
    
answered by 09.10.2018 в 16:38