Search code examples
javascriptjqueryhtmlcsspreloader

Force page preloader to appear before any content


I am implementing a very simple preloader page that is present until the main page content is fully loaded. The loading page works fine but I'm just having a small issue with the main page content showing momentarily before the preloader page is in place, resulting in an unsightly flash of content.

I have provided a live link below as it is difficult to replicate in a fiddle due to the need for load times, can anyone offer some insight into how to ensure the preloader page always loads first?

Thanks.

HTML

<div class='preloader'>
    <div class="preloader-logo">Logo</div>
    <div class="preloader-loading-icon">Loading</div>
</div>

<main>Content goes here, should be hidden initially until fully loaded.</main>

CSS

.preloader {
    display: block;
    position: fixed;
    width: 100%;
    height: 100%;
    overflow: hidden;
    top: 0;
    left: 0;
    z-index: 9999;
    background: rgba(255,102,51,1);
}

.preloader-logo {
    background: url(images/ui-sprite.svg) no-repeat 0 -300px;
    position: absolute;
    width: 140px;
    height: 58px;
    top: 50%;
    left: 50%;
    text-indent: -9999px;
}

.preloader-loading-icon {
    background: url(images/preloader-loading.svg) no-repeat 50%;
    text-indent: -9999px;
    position: relative;
    top: 50%;
    left: 50%;
    margin-top: 90px;
    width: 40px;
    height: 40px;
}

JS

/* Preloader Splash */
$(window).load(function(){
     $('.preloader').fadeOut(500);
});

Link


Solution

  • Set main element to be hidden by default, and show it right before you fadeout the preloader:

    main {
        display: none;
    }
    
    $(window).load(function(){
        $('main').show();
        $('.preloader').fadeOut(500);
    });