Check for image return via Javascript

4

How to check if the image returned with 404 error via javascript.

Below a sample code, I want to check if the get of this image is 404. If I want to put a certain image, if it does not return the image.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <img src="http://pbs.twimg.com/profile_images/438827041199099904/ZLjBL8Tg_normal.jpeg"alt=""/ id="teste">
</body>
</html>
    
asked by anonymous 03.06.2014 / 19:45

4 answers

3

Another solution coming from SOen based on an article that no longer exists today ( link of the Files).

// First a couple helper functions
function $(id) {
    return !id || id.nodeType === 1 ? id : document.getElementById(id);
}
function isType(o,t) {    return (typeof o).indexOf(t.charAt(0).toLowerCase()) === 0;}

// Here's the meat and potatoes
function image(src,cfg) {    var img, prop, target;
    cfg = cfg || (isType(src,'o') ? src : {});

    img = $(src);
    if (img) {
        src = cfg.src || img.src;
    } else {
        img = document.createElement('img');
        src = src || cfg.src;
    }

    if (!src) {
        return null;
    }

    prop = isType(img.naturalWidth,'u') ? 'width' : 'naturalWidth';
    img.alt = cfg.alt || img.alt;

    // Add the image and insert if requested (must be on DOM to load or
    // pull from cache)
    img.src = src;

    target = $(cfg.target);
    if (target) {
        target.insertBefore(img, $(cfg.insertBefore) || null);
    }

    // Loaded?
    if (img.complete) {
        if (img[prop]) {
            if (isType(cfg.success,'f')) {
                cfg.success.call(img);
            }
        } else {
            if (isType(cfg.failure,'f')) {
                cfg.failure.call(img);
            }
        }
    } else {
        if (isType(cfg.success,'f')) {
            img.onload = cfg.success;
        }
        if (isType(cfg.failure,'f')) {
            img.onerror = cfg.failure;
        }
    }

    return img;
}

Usage:

image('http://somedomain.com/image/typooed_url.jpg', {
    success : function () {alert(this.width)},
    failure : function () {alert('Oops!')}
});

image('https://www.gravatar.com/avatar/bac48b9b301f4b2aea7ec399a14b8bc9?s=128&d=identicon&r=PG', {
    success : function () {/** ... */},
    failure : function () {alert('Oops!')},
    target : 'successImageContainer'
});

Demo no Fiddle .

At first glance it seems to be over-resource, but if it were to be seen, if it resulted in a 404 you would have to make some conditions and then some callbacks come in handy.     

03.06.2014 / 19:59
5

You can use a listener for the onerror event:

<img src="http://pbs.twimg.com/profile_images/438827041199099904/ZLjBL8Tg_normal.jpeg"alt=""/ id="teste">
<script>
document.getElementById('teste').onerror = function() {
    alert('Xi, deu erro!');
}
</script>
    
03.06.2014 / 19:49
4

You can make a request HEAD and check the return status of url .

function checkStatus(imageUrl) 
{
   var http = jQuery.ajax(
   {
      type:"HEAD",
      url: imageUrl,
      async: false
    })
  return http.status;
}

And use it this way:

var imageUrl = 'http://pbs.twimg.com/profile_images/438827041199099904/ZLjBL8Tg_normal.jpeg';
var statuscode = checkStatus(imageUrl);

if (statuscode == 200)
{
   // Existe!
} else if (statuscode == 404)
{
   // Não existe!
}
// else if....
    
03.06.2014 / 19:56
2

You can make a load in the url of the image to check if it exists:

function checkImagem(url) {
  var img = '<img src="'+ url +'" />';
  $(img).load(function() {
    $('body').append(url+img);
  }).bind('error', function() {
    alert('imagem: '+url+' não existe');
  });
 }

Example: JSFiddle

    
03.06.2014 / 20:50