4

I'm running a script that is dynamically loading images depending on a few criteria. The script does not know beforehand whether a specific image source actually exists and will thus need to check before displaying the image. I do this by replacing the onerror handler on the element with a function that attempts to gracefully handle the event.

At first glance this works rather well, however even though I have replaced the event, the browser still audits 404 errors in the console which I don't want. Even worse is that IE displays the infamous JS error icon in the status bar which I find rather awkward.

I've tried to summarise the problem in a JSFiddle.

var img = new Image();
img.onerror = function (ev) {
    alert("This does not exist!");
    return true;
}
img.onload = function (ev) {
    document.body.appendChild(this);
}
img.src = "foo.png"; //Missing image

Basically, I want to suppress all error reporting for this element such that the console doesn't get flooded with superfluous error output.

I know that I could solve this by prefetching and evaluating the HTTP headers with AJAX and server side scripting, which while technically a possible solution, is something I would prefer to avoid. However, while I only use standard JS in my example, JQuery code is also acceptable.

I have tried reading up on the event specification, but since web scripting is still the mess of confusing ECMAScript, HTML DOM, client, pixy dust and now HTML5 definitions that we all love to hate, it really didn't make me any wiser. The closest I got was Mozilla's documentation (that interestingly doesn't even state the correct function parameters) which suggested that letting the event return true would suppress errors, but that didn't really work.

Daniel Perván
  • 1,685
  • 13
  • 11

1 Answers1

1

I believe you can not check if image link is broken/does not exist without getting 404 error. Which is actually is information about link is broken.

You mentioned that other way is ajax to check existance...

function UrlExists(url) {
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status != 404;
}

UrlExists('img_url');

but still you will get 404 in console.

Sergei Zahharenko
  • 1,514
  • 12
  • 16
  • I have actually never thought about that AJAX calls also triggers errors, so thanks for that point. However, since I would either way need to support both local and cross-domain images, I would have to do the actual check on server side (i.e. AJAX loads server script that validates the existence through cURL), which is why I didn't want that solution. – Daniel Perván Dec 16 '13 at 13:46
  • so the answer is no ... you can't do it on front side! Yes, server side only. – Sergei Zahharenko Dec 16 '13 at 14:13