View image until the gif is loaded

0

I am loading a gif when the user hover over a certain <div> . I do this using jQuerry with the following code:

$('#vidthumb_' + idDoDiv).attr('src', caminhoParaOGif);

The problem is that the gif takes about 1 second to load, and I wanted to show something (loading image or text) until the gif is loaded and ready to play, how should I change my code? / p>     

asked by anonymous 07.02.2018 / 15:06

2 answers

1

You can add a spinner in CSS after the element <img> , which will be removed after the gif is loaded by onload .

You only need to put the image inside a div (this div will not influence the layout , it's for reference only).

See example (since the transition is very fast, I commented on the line that hides the spinner so you can see it in the example):

caminhoParaOGif = "https://tctechcrunch2011.files.wordpress.com/2015/08/safe_image.gif";

$("#vidthumb_").on("mouseover", function(){
   $(this).after('<span class="loader"></span>');
   $('#vidthumb_')
   .attr('src', caminhoParaOGif)
   .on("load", function(){
//      $(this).next().remove(); // descomente esta linha
   });
});
*{
   position: relative;
}

.loader {
    border: 16px solid #f3f3f3; /* cinza */
    border-top: 16px solid #3498db; /* azul */
    border-radius: 50%;
    width: 30px;
    height: 30px;
    animation: spin 2s linear infinite;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -31px 0 0 -31px; /* metade da soma do width + 2x a borda*/
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divstyle="display: inline-block;">
   <img src="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg"height="200" width="200" id="vidthumb_" />
</div>
    
07.02.2018 / 15:48
0

As you are assigning the image via script, it takes some time to load into the document. One tip is to put a gif / image that you want to stay until your image loads directly into the element, so when the user hover over the element, the image will be displayed until the new image is assigned to the src. Example:

$('#img').mouseenter(function(){
  $(this).attr('src','http://www.topimagens.com.br/imagens/imagens-mais-novas.jpg');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><imgid="img" src="https://media2.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif"/>
    
07.02.2018 / 15:19