Preload images before opening the page

297 views Asked by At

I am designing a index page that has a pretty big background image (I do not want to make it smaller since I don't want the image to have noise and distort on bigger screens) and what I want is when you access that index page, before displaying the content to show you a preloader .gif and preload the background image and only after the image is loaded to let you see the content.

I want this because I don't want people with slower specs on the PC or a bad internet connection to see how that background image is being loaded line by line.

CSS :

<style> 
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }
</style>

Jquery :

<script>
    $(function() {   

        var theWindow        = $(window),
            $bg              = $("#bg"),
            aspectRatio      = $bg.width() / $bg.height();

        function resizeBg() {

        if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
            $bg
            .removeClass()
            .addClass('bgheight');
        } else {
            $bg
            .removeClass()
            .addClass('bgwidth');
            }

        }

            theWindow.resize(function() {
                resizeBg();
            }).trigger("resize");

    });
</script>

And HTML :

<img src="images/bg.jpg" id="bg" alt="">
1

There are 1 answers

1
wawan On

HTML

<img src="images/bg.jpg" id="bg" alt="" class="notloaded">

CSS

.notloaded{
    display:none;
}

JS

$( "#bg" ).load(function() {
    $(this).removeClass("notloaded");
    resizeBg();
});

This technic is not fully compatible with old browser. See https://github.com/desandro/imagesloaded to use an efficient solution.