The images which are wouldn’t successfully load on the web page will show nothing when the source does not exist.
It looks bad when there are many images and some of them are missing.
For solving this you need to look through all the pages and find the broken images and fix them manually time to time. It is a time-consuming process.
In this tutorial, I will show you two examples, to automatically detect the broken images and replace with another image.
- In the first one, I am using the jQuery, and
- In the second, using AJAX with jQuery
Contents
1. With jQuery
Bind error
event on the img
element. It gets triggered when the image will not successfully load on the web page.
Using this to replace the image source with the default image.
Example
$(document).ready(function(){ $("img").bind("error",function(){ // Replacing image source $(this).attr("src","images/noimage.png"); }); });
With JavaScript
You need to define onerror
attribute in the image elements and perform image replace operation.
<img onerror='this.src="images/noimage.png"' src='image.png'/>
Problem
Both codes work fine until the replacing image exists on your server. But, by chance, it gets removed or the name of the image is renamed in this case when you load the page you see the flickering effect on the image which does not exist.
This is because when the image does not exist then it triggered error
event now when you try to replace the image with another image which also doesn’t exist then it again triggers error
event.
It becomes the never-ending loop.
For solving this I am using AJAX.
2. With jQuery and AJAX
Looping through all image elements and sending AJAX GET request to image source for the check if the source exists or not. If it doesn’t exist then it goes to the error
function. From their handle the image.
If the replacement file also doesn’t exist then hide the image.
Example
$(document).ready(function(){ // Looping through all image elements $("img").each( function () { var element = $(this); $.ajax({ url:$(this).attr('src'), type:'get', async: false, error:function(response){ var replace_src = "images/noimage.png"; // Again check the default image $.ajax({ url: replace_src, type:'get', async: false, success: function(){ $(element).attr('src', replace_src); }, error:function(response){ $(element).hide(); } }); } }); }); });
3. Demo
Here, the third image is not available on the server.
4. Conclusion
In the tutorial, I used the error event to update the image source with the default image when the image file doesn’t exist.
You can also handle with AJAX request.
I hope this may help you and if you know some other better solution to check the source of the broken images then let me know in the comment section.
If you found this tutorial helpful then don't forget to share.