jQuery loading screen with minimum viewing time

2019-08-23 03:53发布

so i have this loading screen that displays information while the page is loading but because of faster internet speeds this can be displayed in a flash.. I would like to add a minimum display time! this is my current code

jQuery(window).load(function() {
    jQuery('.pageLoad').animate({
        opacity: 0
    }, 800, function() {
        jQuery('.pageLoad').css({
            display: 'none'
        });
    });
});

How can i do this?

2条回答
迷人小祖宗
2楼-- · 2019-08-23 04:05

You could put your fade-out method in a function and call that after an xx number of seconds from $(document).ready():

var timeoutID;

jQuery(document).ready(function() {
    // start hiding the message after 2 seconds
    timeoutID = window.setTimeout(hideMessage, 2000);
});

function hideMessage() {
    jQuery('.pageLoad').animate({
        opacity: 0
    }, 800, function() {
        jQuery('.pageLoad').css({
            display: 'none'
        });
    });
}
查看更多
欢心
3楼-- · 2019-08-23 04:26

As mentioned by @Rayf, if that piece of info should be read, regardless of page loading speed, you should add some delay to it like this:

// time to read the message...adjust it to the time you feel is right
var msgDisplayTime = 5000,
    interval = 0,
    loaded = false,
    delayed = false,
    fadeLoader = function () {
      jQuery('.pageLoad').animate({opacity: 0}, 800, function () {
          jQuery('.pageLoad').css({display: 'none'});
      });
    };

//timeout for your desired delay time
//it will ask if it is already loaded after delay ends
//triggering the fading of loading overlay
timeout = setTimeout(function(){
  delayed = true;
  if(loaded){
    fadeLoader();
  }
},msgDisplayTime);


//when loaded, it will wait until delay happened
//if not, it will delegate the execution to the timeout
// so at the end, it will be triggered after the delay or
//loading time, in case it longer than desired delay
jQuery(window).load(function(){
  loaded = true;
  if(delayed){
    fadeLoader();
  }
});

Inside comments is the roughly explanation about how it works

查看更多
登录 后发表回答