I have a web page that includes 10's of thousands of images. Sometimes the image isn't available so a broken image is displayed in the clients browser.
The broken image is in the following URL format: www.domain.com/t.php?src=p/dd5e5b08_1.jpg.
How do I use jQuery to get the set of images, filter it to broken images then replace the src
?
The following does not work:
above the closing </head>
tag
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
above the closing tag
<script type="text/javascript">
$(window).load(function() {
$("img").each(function(){
var image = $(this);
if(image.context.naturalWidth == 0 || image.readyState == 'uninitialized'){
$(image).unbind("error").attr("src", "/images/no_image.png");
}
});
});
</script>
This code might help you:
function imgError(image){
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
<img src="image.png" onerror="imgError(this);"/>
Try CodeFiddle Demo
This may help you:
$(document).ready(function () {
let images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'];
let image_html = '';
$.each(images, (key, value) => {
image_html += '<img src="img/' + value + '"/>';
});
$('#imgcontainer').html(image_html);
$('img').on('error', function () {
$(this).replaceWith('<img src="img/no-photo.jpg"/>');
});
});