You can do a little trick and hide the "text" inside the image if the image has no src
attribute (or its empty).
(You can hide the text in many ways I choose one)
.test {
display: block;
width: 200px;
height: 82px;
background-size: 200px 82px;
background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJr81CRJeZGFiBsA9_AOyyxegiIPctdcbNfHThnpnclmFH-mJwoQ");
}
img:not([src]) {
font-size: 0;
position: relative;
}
img:not([src]):after {
font-size: 18px;
border: 1px solid black;
box-sizing: border-box;
content: attr(alt);
z-index: -1;
height: 100%;
width: 100%;
position: absolute;
top: 0;
left: 0
}
<img class="test" alt="My background image">
The completion for the css (the :after
part) received from @Ihazkode.
For displaying the alt
after the image loading you can load (with javascript) the image first, then, put it in the image and display the alt
. (Based on this answer)
$('[data-image]').each(function() {
var $this = $(this);
var alt = $this.attr('alt');
var src = $(this).attr('data-image');
$this.removeAttr('alt');
$('<img/>').attr('src', src).on('load', function() {
$(this).remove();
// simulate the delay for heavy image
setTimeout(function(){
$this.css('background', 'url(' + src + ')').attr('alt', alt);
}, 1000);
}).on('error', function() {
$this.attr('alt', alt);
});
});
.test {
display: block;
width: 200px;
height: 82px;
background-size: 200px 82px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="test" alt="My background image" data-image="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJr81CRJeZGFiBsA9_AOyyxegiIPctdcbNfHThnpnclmFH-mJwoQ">