Search code examples
javascriptjqueryfadeoutpreloadpreloading

Set Time for fading out PreLoad Screen using jQuery


I need some help. I have tried to create a custom preload screen like this. But in this tutorial the author fades out his overlaying element after three seconds (fakes it). I know that to fade out the preload screen after page loading, I need to use $(window).load():

$(window).load(function(){
       // PAGE IS FULLY LOADED  
       // FADE OUT YOUR OVERLAYING DIV
});

But the point is I need loading progress. Actually, I want it to last at least 3 seconds and if the load time is 4 seconds for example, it lasts 4 seconds. But if the loading time is less than 3 seconds, it still lasts 3 seconds.

I have a Logo that is drawn using stroke-dashoffset and stroke-dasharray, so I need code to give it enough time to draw it.

Plus, I would like to have a counter to get the remaining time until fully loaded. I'm going to convert it to percent of loading progress.

Can anybody help me do this, please?


Solution

  • The remaining loading time of a page is unknowable. Network congestion, errors, processor speed (server and client), GPU speed, and many other factors not visible to the client all affect load time. You do not have enough information to know how long the request(s) and page rendering will take.

    As per this piece of your question:

    Actually, I want it to last at least 3 seconds and if the load time is 4 seconds for example, it lasts 4 seconds. But if the loading time is less than 3 seconds, it still lasts 3 seconds.

    Then simply use a setTimeout with 3000 milliseconds to fade out the loading screen. Use a couple of variables to track if the time has elapsed and the page is loaded:

    var pageLoaded = false;
    var timeElapsed = false;
    
    function fadeOutLoadScreen() {
        if(timeElapsed && pageLoaded) {
            // do fadeOut stuff here
        }
    }
    
    setTimeout(function(){ 
        timeElapsed = true;
        fadeOutLoadScreen();
    }, 3000);
    
    $(window).load(function(){
        pageLoaded = true;
        fadeOutLoadScreen();
    });