Is there any way to render a default image in an HTML tag, in case the
src
attribute is invalid (using only HTML)? If not, what would
Google threw out this page to the "image fallback html" keywords, but because non of the above helped me, and I was looking for a "svg fallback support for IE below 9", I kept on searching and this is what I found:
<img src="base-image.svg" alt="picture" />
<!--[if (lte IE 8)|(!IE)]><image src="fallback-image.png" alt="picture" /><![endif]-->
It might be off-topic, but it resolved my own issue and it might help someone else too.
Using Jquery you could do something like this:
$(document).ready(function() {
if ($("img").attr("src") != null)
{
if ($("img").attr("src").toString() == "")
{
$("img").attr("src", "images/default.jpg");
}
}
else
{
$("img").attr("src", "images/default.jpg");
}
});
If you have created dynamic Web project and have placed the required image in WebContent then you can access the image by using below mentioned code in Spring MVC:
<img src="Refresh.png" alt="Refresh" height="50" width="50">
You can also create folder named img and place the image inside the folder img and place that img folder inside WebContent then you can access the image by using below mentioned code:
<img src="img/Refresh.png" alt="Refresh" height="50" width="50">
a simple img-element is not very flexible so i combined it with a picture-element. this way no CSS is needed. when an error occurs, all srcset's are set to the fallback version. a broken link image is not showing up. it does not load unneeded image versions. the picture-element supports responsive design and multiple fallbacks for types that are not supported by the browser.
<picture>
<source id="s1" srcset="image1_not_supported_by_browser.webp" type="image/webp">
<source id="s2" srcset="image2_broken_link.png" type="image/png">
<img src="image3_fallback.jpg" alt="" onerror="this.onerror=null;document.getElementById('s1').srcset=document.getElementById('s2').srcset=this.src;">
</picture>
angular2:
<img src="{{foo.url}}" onerror="this.src='path/to/altimg.png'">
I recently had to build a fall back system which included any number of fallback images. Here's how I did it using a simple JavaScript function.
HTML
<img src="some_image.tiff"
onerror="fallBackImg(this);"
data-fallIndex="1"
data-fallback1="some_image.png"
data-fallback2="some_image.jpg">
JavaScript
function fallBackImg(elem){
elem.onerror = null;
let index = +elem.dataset.fallIndex;
elem.src = elem.dataset[`fallback${index}`];
index++;
elem.dataset.fallbackindex = index;
}
I feel like it's a pretty lightweight way of handling many fallback images.