I have a web page that includes a bunch of images. Sometimes the image isn\'t available, so a broken image is displayed in the client\'s browser.
How do I use jQuery
Better call using
jQuery(window).load(function(){
$.imgReload();
});
Because using document.ready
doesn't necessary imply that images are loaded, only the HTML. Thus, there is no need for a delayed call.
If the image cannot be loaded (for example, because it is not present at the supplied URL), image URL will be changed into default,
For more about .error()
$('img').on('error', function (e) {
$(this).attr('src', 'broken.png');
});
Here is an example using the HTML5 Image object wrapped by JQuery. Call the load function for the primary image URL and if that load causes an error, replace the src attribute of the image with a backup URL.
function loadImageUseBackupUrlOnError(imgId, primaryUrl, backupUrl) {
var $img = $('#' + imgId);
$(new Image()).load().error(function() {
$img.attr('src', backupUrl);
}).attr('src', primaryUrl)
}
<img id="myImage" src="primary-image-url"/>
<script>
loadImageUseBackupUrlOnError('myImage','primary-image-url','backup-image-url');
</script>
I use lazy load and have to do this in order to make it work properly:
lazyload();
var errorURL = "https://example.com/thisimageexist.png";
$(document).ready(function () {
$('[data-src]').on("error", function () {
$(this).attr('src', errorURL);
});
});
I am not sure if there is a better way, but I can think of a hack to get it - you could Ajax post to the img URL, and parse the response to see if the image actually came back. If it came back as a 404 or something, then swap out the img. Though I expect this to be quite slow.
By using Prestaul's answer, I added some checks and I prefer to use the jQuery way.
<img src="image1.png" onerror="imgError(this,1);"/>
<img src="image2.png" onerror="imgError(this,2);"/>
function imgError(image, type) {
if (typeof jQuery !== 'undefined') {
var imgWidth=$(image).attr("width");
var imgHeight=$(image).attr("height");
// Type 1 puts a placeholder image
// Type 2 hides img tag
if (type == 1) {
if (typeof imgWidth !== 'undefined' && typeof imgHeight !== 'undefined') {
$(image).attr("src", "http://lorempixel.com/" + imgWidth + "/" + imgHeight + "/");
} else {
$(image).attr("src", "http://lorempixel.com/200/200/");
}
} else if (type == 2) {
$(image).hide();
}
}
return true;
}