Use jQuery to Replace Broken Images using AJAX

Sam Deering

Expanding on my previous post about detecting and removing broken images I have delved further into the realms of using jQuery to replace broken images using AJAX.

In most browsers the ALT tag is shown if the image is not found. This could be a problem if the image is small and the ALT tag is long as it seems the output width of the element is not forced by the length of the alt tag. So it makes sense to replace broken images with a default image.

Get information about the current images on page

$("img").each( function () {
	console.log($(this).attr('src')+ ' ' + $(this).attr('alt') + ' ' + $(this).width());
});

Using AJAX to test if the image exists

$("img").each( function () 
{
	$.ajax({
		url:$(this).attr('src'),
		type:'HEAD',
		error:
			function(){
				//image doesn't exist
				console.log('ERROR');
			},
		success:
			function(){
				//image exists
				console.log('success');
			}
	});
});
/*
Output:
success
success
ERROR
success
success
*/

Refresh image

d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime()); //cache flush

Fix broken images using ajax

Note the additions of _this and e.status.

$(".productBoxImage img").each( function () 
{
	var _this = $(this);
	
	$.ajax({
		url:$(this).attr('src'),
		type:'HEAD',
		async: false,
		error:
			function(e)
			{
				if (e.status == '404') {
					$(_this).attr('src',[replaceImageUrl]);
				}
			}
	});
});

Non ajax function version

/**
 * Returns true if image is broken, false otherwise
 * @param {jQuery} image A single image element
 * @return {Boolean}
 */
isImageBroken: function(image)
{
	$image = $(image);
	if($image.attr('complete') == false || $image.attr('naturalWidth') == 0 || $image.attr('readyState') == 'uninitialized' || this.trim($image.attr('src')) == '')
	{
		return true;
	}
	return false;
},

Hope that all made sense, if not post a comment and i’ll answer your question! :)

Win an Annual Membership to Learnable,

SitePoint's Learning Platform