Delay jQuery effects whilst page is loading

2019-08-06 03:43发布

问题:

I have this bit of code:

$("#comingsoon, #1, #2, #3").hide().each(function(i) {
    $(this).delay(i * 500).slideDown(1500);
});

Which basically fades in a series of objects on my page, problem is that the animation lags horribly when the flash banner at the top of the page is loading. I would like to delay the entire jQuery animation for about 2-3 seconds.

Anyone got any ideas.

回答1:

I assume that you are using $(document).ready() to fire your code.

If you want to wait until the DOM and all of the page content has loaded, you can use $(document).bind("onload", ...);.



回答2:

Since you're already using delay, you could just add a fixed interval to your current variable interval:

$("#comingsoon, #1, #2, #3").hide().each(function(i) {
  $(this).delay(2500 + i*500).slideDown(1500);
});

(That 2500 adds a 2.5 second delay before the slideDowns start.)

If you want to delay hiding as well, put your whole thing in a delayed function:

setTimeout(function() {
    $("#comingsoon, #1, #2, #3").hide().each(function(i) {
      $(this).delay(i*500).slideDown(1500);
    });
}, 2500);

That won't even hide things until 2.5 seconds after that code is run.

See also John Gietzen's answer: If you want to wait until all page content is loaded (which can be a long time, but perhaps exactly what you want here), use the window load event instead of jQuery.ready.



回答3:

$(window).load(function () {
     $("#comingsoon, #1, #2, #3").hide().each(function(i) {
     $(this).delay(i*500).slideDown(1500);
     });
});

That executes when the window loads fully and not when the DOM is ready.



回答4:

You could always use the setTimeout() function.

setTimeout(   function() {

    $("#comingsoon, #1, #2, #3").hide().each(function(i) {
        $(this).delay(i*500).slideDown(1500);
    });

}, 3000);