Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading pages with jQuery

Tags:

jquery

css

I have an image heavy website, and to improve the loading of it, I have implemented a loading screen. At the moment, it is a white overlay with this css:

#loader{
    width: 100%;
    height: 100%;
    position: fixed;
    z-index: 9999999999999999;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('loader.gif') 50% 50% no-repeat rgb(255,255,255);
} 

This is the jQuery that I have at the moment:

$(window).load( function(){

    $("#loader").fadeOut("slow");

});

At the moment this loading screen loads at the same time as the rest of the website, and it looks messy.

How would I be able to only load the rest of the page once the loading page it loaded and displayed?

like image 619
Sam Avatar asked May 06 '26 07:05

Sam


1 Answers

Using the solution in jQuery callback on image load (even when the image is cached) this:

$(window).load( function(){
    var totalImages = $('img').length, // count how many images are in the page
        loadedImages = 0; // keep track of how many have loaded

    // listen to the load event on every image only one time
    $("img").one("load", function() {
        loadedImages++;  // when an image loads, increment the counter
        if (loadedImages == totalImages){
            // the number of images loaded equals the number of total images in the page
            // we can consider the loading process finished here
            $("#loader").fadeOut("slow");     
        }
    }).each(function() {
        // some images might have already loaded, eg. from cache
        // iterate over all of them and if the property 'complete' exists
        // manually fire the load event above
        if(this.complete) $(this).load();
    });
});
like image 170
Juank Avatar answered May 09 '26 10:05

Juank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!