How to load default image if src="" can not find?

10

Is there any way to load a default image using only HTML , if the first src="" can not find the file?

<img src="ola_mundo.png" alt="Olá Mundo"> // Existe algum atributo para isso?
    
asked by anonymous 22.11.2016 / 14:14

2 answers

5

Other simpler fallbacks you can try, with javascript:

<img src="imagem-nao-existe.png" onerror="this.src='fallback.png'">

An example in @Randrade's jsfiddle: link

Sem error
<br>

<img src="http://previews.123rf.com/images/otnaydur/otnaydur1103/otnaydur110300040/9112843-Gold-coins-stack-over-scater-coins-Stock-Photo-bar.jpg"alt="Olá Mundo" onerror="this.onerror=null;this.src='http://logz.io/wp-content/uploads/2016/02/stack-overflow-logo.png';"
>

<br>Com error
<br>

<img src="loading.gif" alt="Olá Mundo" onerror="this.src='http://logz.io/wp-content/uploads/2016/02/stack-overflow-logo.png';" >

With CSS (requires fixed size):

<style>
.image {
     width: 620px;
     height: 480x;
}
</style>

<div class="image" style="background: url(foto-nao-existe.png), url(fallback.png)"></div>
    
22.11.2016 / 14:35
6

I found this solution ...

<object data="https://img.com.br/no_existe.jpg" type="image/png">
  <img src="http://farm2.static.flickr.com/1094/984405951_34580c3cb9.jpg"/></object>

Nessa question

    
22.11.2016 / 14:26