Detect When an Image Fails to Load in JavaScript

Detect when an image fails to load in JavaScript

You could try the following code. I can't vouch for browser compatibility though, so you'll have to test that.

function testImage(URL) {
var tester=new Image();
tester.onload=imageFound;
tester.onerror=imageNotFound;
tester.src=URL;
}

function imageFound() {
alert('That image is found and loaded');
}

function imageNotFound() {
alert('That image was not found.');
}

testImage("http://foo.com/bar.jpg");

And my sympathies for the jQuery-resistant boss!

How can I detect WHY an image failed to load?

From the client side, you can try to access image by making an ajax call then parsing the response. Easily done using jQuery.

var call = $.ajax( "image.img" )
.fail(function( call, textStatus ) {
alert( "Request failed: " + textStatus );
});

From the server side, you can check the server logs, search for the correct request and see what happened. If request never came to the server it might be network/routing/firewall problem.

Steps to do this, however, are highly dependent on what is used in the backend.

Detect when image fails to load

The cause of your issue is because the error event does not bubble, hence the delegated event handler you're attempting to use will not pick up the event from the document.

To fix this you'll need to use a static event handler defined directly on the img elements:

$('img[src*="/image/path/"]').on('error', function() {  console.log('error loading image ' + $(this).attr('src'));});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script><img src="/my/image/path/foo/bar.jpg" />

Check if an image is loaded (no errors) with jQuery

Another option is to trigger the onload and/or onerror events by creating an in memory image element and setting its src attribute to the original src attribute of the original image. Here's an example of what I mean:

$("<img/>")
.on('load', function() { console.log("image loaded correctly"); })
.on('error', function() { console.log("error loading image"); })
.attr("src", $(originalImage).attr("src"))
;

Hope this helps!

Checking for failed image load

Use on('error', handler) for catching 404

var $img = $("<img src='https://www.example.com/path' />").on('load', function() {
console.log('img loaded');

}).on('error', function(event){

console.log('img failed to load');
console.log(event)
})

How to detect image load failure and if fail, attempt reload until success?

Here something I compiled which might help. I couldn't manage to do testing of this please let me know if you are having any issues.

$(function() {
var $images = $('img.imageClassUpdateAtInterval:not([src="/assets/spinner.gif"])');

// Now, no such image with
// a spinner
if($images.length === 0 && window.imageLocator)
clearInterval(window.imageLocator);

window.imageLocator = setInterval(function() {
$images.each(function() {
$this = $(this);
if (!$this.data('src')) {
$this.data('src', $this.prop('src'));
}

$this.prop('src', $this.data('src') + '?timestamp=' + new Date().getTime());
console.log($this.prop('src'));
});
}, 60 * 1000);

// suppose, an error occured during
// locating the src (source) of the
// image - image not found, network
// unable to locate the resource etc.
// it will fall in each time on error
// occurred
$('img.imageClassUpdateAtInterval').error(
function () {
// set a broken image
$(this).unbind("error").attr("src", "/assets/broken.gif");
// setting this up in relative
// position
$(this).css("position", "relative");
$(this).apppend("<span>Error occured</span>");
$(this).find("span").css({"position": "absolute", "background-color": "#252525", "padding": ".3em", "bottom": "0"});
});

});

The above solution is compiled from two different solutions commenced by @user113716 and @travis

Is there code that can be used to alert user when image does not load?

Just use onerror

<img src="../missing-file.jpg" onerror="myAlertFunction()">
function myAlertFunction() {
alert('The image could not be loaded.');
}

How to tell if an image was not loaded in Angular?

you can use (error) that way to set default image in case of 404, you can set a default pic from asset or from placeholder

<img [src]="slide.img" (error)="slide.img='./assets/img/default.jpg'">

Detect failed to load image with javascript

Use an event handler for the error event, e.g.

print("<img src=\"data:image/jpeg;base64," . $base64Img . "\" onerror=\"this.src='ieSafeImg.jpg';\" />");


Related Topics



Leave a reply



Submit