简体   繁体   中英

How do I delay the loading of an Image, so that i can display a loading.gif for 2 or 3 seconds before the image loads? (using jQuery/javascript)

I have two images:

-loading.gif (which is the loading animation)

-scenery.jpeg (which is i what i want to display after the loading process);

because scenery.jpeg is a small file, using load() function will only skip the loading.gif

so when I click the button how do i display the loading.gif for 3 seconds before it loads scenery.jpeg?

advance thanks! :D

so i have this html file:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>

$(document).ready(function(){
    $("#loading , #picture").hide();

    $("#button1").click(function(){
        /* the loading.gif shows then after 3 seconds scenery.jpeg will use fadeIn() */
    });
});
</script>

</head>

<body>
<button id="button1">Click Me!</button>
<img id="loading" src="loading.gif"/>>
<img id="picture" src="scenery.jpeg"/>
</body>
</html>

You can use delay() in this case:

$("#button1").click(function(){
    $("#loading").fadeIn().delay(3000).fadeOut('slow', function() {
       $(this).next().fadeIn() 
    });
});

Demo

Try this one:

$('#loading, #picture').hide();
$('#button1').on('click', function() {
  $('#loading').show();
  setTimeout(function() {
    $('#loading, #picture').toggle();
  }, 3000);
});

One of the ways would be:

  1. Replace image src with throbber src .
  2. Create new Image object, set it's src to one of image.
  3. Add load event listener on Image , and set img src inside setTimeout with desired value.

The function the does that:

function delayLoad (img, throbber, delay) {
  var src = img.src,
      hidden = new Image();

  img.src = throbber;

  hidden.addEventListener("load", function (e) {
    setTimeout(function () {
      img.src = src;
    }, delay);
  });

  hidden.src = src;
}

Use it like this:

delayLoad(document.querySelector("img"), "http://www.mfshop.ru/images/throbber.gif", 3000);

JSBin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM