Mostrar o carregamento do gif enquanto a imagem está a carregar

Fiz um código onde o utilizador pode enviar algumas imagens de um zip. Na página seguinte eu preciso mostrar todas as imagens seperatly em uma moldura 85*85 px.

o problema é que pode levar algum tempo para todas as imagens carregarem. Então eu quero mostrar um GIF de carregamento enquanto o usuário espera pela imagem para carregar.

configurei o src das imagens como the loading gifs, enquanto criei algumas caixas de controlo com a verdadeira fonte como id

echo "<td><img src=\"beelden/ajax-loader-black-16.png\" id=\"img".$image."\" style=\" width: 85px; height: 85px; border: 1px solid gray; background-color: #fff; padding: 10px;\">";
echo "<input type=\"checkbox\" id=\"img[".$image."]\" name=\"check_image[]\" value=\"".$filename."\" /></td>";
<input type="hidden" name="aantal" id="aantal" value="<?=$image?>" >
Depois criei alguns javascript para verificar se a imagem é carregada, e quando é, é suposto substituir a fonte da imagem.

<script>
    var aantal = document.getElementById("aantal").value;
    for(var i = 0; i < aantal; i++){
        var source = document.getElementById("img["+i+"]").value;
        var img = new Image();
        img.onload = function(){
            $("#img"+i).attr('src', source);
        }();
        img.src = source;
    }
</script>
Mas isto não funciona como eu esperava, acho que dispara para todas as imagens assim que o primeiro está carregado. Alguma ideia do que estou a fazer de errado ou como resolver isto?

Author: PirateSoul, 2015-04-20

1 answers

Você pode definir o fundo de uma imagem para o GIF de carregamento. É um simples truque da css. Não precisarias de fazer um guião do js.

.loading {
  background: transparent url('http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif') center no-repeat;
}
<img class="loading" src="http://placehold.it/106&text=1" width="106px" height="106px" />
<img class="loading" src="http://placehold.it/106&text=2" width="106px" height="106px" />
<img class="loading" src="http://placehold.it/106&text=3" width="106px" height="106px" />
<img class="loading" src="http://placehold.it/106&text=4" width="106px" height="106px" />
<img class="loading" src="http://placehold.it/106&text=5" width="106px" height="106px" />
<img class="loading" src="http://placehold.it/106&text=6" width="106px" height="106px" />
<img class="loading" src="http://placehold.it/106&text=7" width="106px" height="106px" />

Actualização:

No caso de você ter imagens transparentes, a história torna-se um pouco mais complicada, mas, ainda pode ser feito com css e alguns elementos div.

.image-wrapper {
  overflow: hidden;
  width: 106px;
  height: 106px;
  display: inline-block;
}

.image-wrapper img {
  float: left;
  display: block;
  opacity: 0.2; /* simulating a semitransparent image */
}

.image-wrapper:after, .loading {
  content: ' ';
  background: transparent url('http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif')  center no-repeat ;
  background-size : auto 100%;
  width: 106px;
  height: 106px;
  float: left;
  display: block;
}
<div class="image-wrapper">
  <!-- simulates a hard loading image -->
  <img src="http://placehold.it/not-existing" alt="" />
</div>
<div class="image-wrapper">
  <img src="http://placehold.it/106x106&text=2" alt="" />
</div>
<div class="image-wrapper">
  <img src="http://placehold.it/106x106&text=3" alt="" />
</div>
<div class="image-wrapper">
  <img src="http://placehold.it/106x106&text=4" alt="" />
</div>
<div class="image-wrapper">
  <img src="http://placehold.it/106x106&text=5"  alt="" />
</div>
<div class="image-wrapper">
  <img src="http://placehold.it/106x106&text=6"  alt="" />
</div>
<div class="image-wrapper">
  <img src="http://placehold.it/106x106&text=7"  alt="" />
</div>

Infelizmente, o navegador adiciona um ícone partido ou um ? ao carregar, é por isso que a imagem contém um vazio alt;

Actualização 2:

A segunda variante depende muito do tamanho da imagem, se você tiver tamanhos diferentes do gif de carregamento, não será empurrado correctamente, como uma alternativa seria usar a primeira variante e um pequeno script js que irá remover o fundo assim que a imagem for carregada:

$('img').load(function(){
   $(this).css('background','none');
});
   .loading {
      background: transparent url('http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif') center no-repeat;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="loading" src="http://upload.wikimedia.org/wikipedia/en/2/2d/SRU-Logo-Transparent.png" width="106px" height="106px" />
    <img class="loading" src="http://placehold.it/106&text=2" width="106px" height="106px" />
    <img class="loading" src="http://placehold.it/106&text=3" width="106px" height="106px" />
    <img class="loading" src="http://placehold.it/106&text=4" width="106px" height="106px" />
    <img class="loading" src="http://placehold.it/106&text=5" width="106px" height="106px" />
    <img class="loading" src="http://placehold.it/106&text=6" width="106px" height="106px" />
    <img class="loading" src="http://placehold.it/106&text=7" width="106px" height="106px" />
 22
Author: Tiberiu C., 2015-04-20 09:39:17