Rid Iculous
Rid Iculous

Reputation: 3962

Is it possible to catch failed IMG loads when the server sends HTML instead of image data?

I have a website that links to different images on other websites. Sometimes these images have been removed or the domains are no longer live, etc. To not show these images and remove them instead I'm using jQuery to do this:

 // catch image load errors
$( "img" ).error(function() { 

 // read out image source:
 var src = $(this).attr('src');

// post the source to the server for the image to be removed    
 $.post("/pajax/image/notLoaded/", {url:src},
    function success(obj) {

       if(obj.status =='ok'){
            console.log('removed: '+src);
        }

      },
   "json" );

 // hide the image & its container div
    $( this ).hide();
    $( this ).closest(".item-img").hide();

This works fine for images that are no longer live and no data is been sent. However, often enough an HTML page is sent instead in which case jQuery doesn't throw the error, but the console shows "Resource interpreted as Image but transferred with MIME type text/html:"

Is there a way to catch this with jQuery?

Upvotes: 2

Views: 1255

Answers (2)

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

Your question is very similar to this one:

jQuery/JavaScript to replace broken images

Rather than using jQuery and trying to attach an event, I've found it most reliable to write the <img...> element this way:

<img src="image.png" onerror="this.style.display='none';"/>

Upvotes: 2

user3886234
user3886234

Reputation:

I don't know how jQuery assigns onerror, but I'm successfully getting / handling an error when the MIME type doesn't match.

JSFiddle example.

If you still can't get it to work, my next suggestion is to send an AJAX request and attempt to retrieve the MIME type. I'm pretty sure it won't work if you are hotlinking, though.

You could do something like:

var url = document.getElementsByTagName('img')[0].src
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send(null);

console.log(xhr.getAllResponseHeaders());
//or
console.log(xhr.getResponseHeader("content-type"));

Upvotes: 0

Related Questions