Check for image return via Javascript

Asked

Viewed 4,583 times

4

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

Below an example code, I want to check if the get of this image is 404. If I want to put a certain image, if it is not going to 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>

4 answers

5

You can use a Library for the event onerror:

<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>
  • Thank you very much, but I did the test here and it does not do the Alert, it is as if it returns something. But if you access this image you will see that it gives error in console 404.

  • I did a test and it seemed to work: http://jsbin.com/saritewu/1/edit

  • Rolled here @bfaretto. Even thanks :)

  • 1

    In this link of the Archives I mentioned in my reply the author lists a number of peculiarities between browsers regarding onerror (and onload). JS is not my strong enough to say whether trusting completely (and solely) in onerror is safe or not.

  • Thanks @Brunoaugusto, I read the link.

  • So what? Does it influence anything?

  • 1

    @Brunoaugusto From what I understand, roughly speaking, the biggest problem is with cache. Whether the goal is to control the loading of something that may or may not be accessible intermittently, onerror can be problem. If it is to check if a resource does not exist and never existed, onerror must be sufficient.

Show 2 more comments

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 that 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....
  • All right, I’ll test it this way.

3


Another solution coming soen based on an article that today no longer exists (link from the Archives).

// 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;
}

Use:

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 in the Fiddle.

At first glance it looks like an over-appeal, but if it turns out to be a 404 you’d have to make some conditions and such then some callbacks come in handy.

  • Poxa ! Complete @Brunoaugusto, very good indeed.

2

You can make a load image url to check if there is:

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

  • 1

    To work in new versions of Jquery use so $(img).on("load", function() {

Browser other questions tagged

You are not signed in. Login or sign up in order to post.