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
This has been frustrating me for years. My CSS fix sets a background image on the img
. When a dynamic image src
doesn't load to the foreground, a placeholder is visible on the img
's bg. This works if your images have a default size (e.g. height
, min-height
, width
and/or min-width
).
You'll see the broken image icon but it's an improvement. Tested down to IE9 successfully. iOS Safari and Chrome don't even show a broken icon.
.dynamicContainer img {
background: url('/images/placeholder.png');
background-size: contain;
}
Add a little animation to give src
time to load without a background flicker. Chrome fades in the background smoothly but desktop Safari doesn't.
.dynamicContainer img {
background: url('/images/placeholder.png');
background-size: contain;
animation: fadein 1s;
}
@keyframes fadein {
0% { opacity: 0.0; }
50% { opacity: 0.5; }
100% { opacity: 1.0; }
}