Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide loading gif after ajax callback

I have a simple question but I couldn't find a clean answer. I need to load heavy images after an ajax call and I want to use an animated gif as a pre-loader. I'm using the follow code:

function loadProducts(url) {
    $("#loading").show();
    $('#inner').fadeOut(1).load(url + ' .product-list', function() {
        $('#inner').fadeIn(1000, function() {
            $("#loading").hide();
        });
    });
}

The #loading is hiding when the HTML is loaded .load(url + ' .product-list'. The problem is that the heavy images are still rendering on the screen and I would like to keep showing the animated .gif until the renders of the images are finished. Is there a way to know when the images on the screen are rendered?. Thanks in advance.

like image 817
Pablo Avatar asked Mar 31 '14 05:03

Pablo


People also ask

How display loading image or loader when Ajax call is in progress?

You can display the image just before this call to $. ajax() and then hide/remove the image in the post handler function (just before your . empty()/. append(data) calls.

How do you show a loader until Ajax response?

Answer: Use the ajaxStart() and ajaxStop() MethodWhile working with Ajax, showing a loading spinner or displaying a message with some animation like "Loading... Please Wait" is popular way to indicate the user that Ajax request is in progress.


1 Answers

You can use promises to check when all the images have loaded, and then remove the loading gif.

This creates a promise that is resolved when the image has loaded, all the promises are kept in an array, and when all promises are resolved, i.e. all images are loaded, the callback fires.

function loadProducts(url) {
    $("#loading").show();

    $('#inner').fadeOut(1).load(url + ' .product-list', function() {

        var promises = [];

        $('#inner').find('img').each(function(_, image) {
            var img = new Image(), 
                def = new $.Deferred();

            img.onload = function() {
                def.resolve();
            }

            promises.push( def.promise() );

            img.src = image.src;
            if (img.complete) img.onload();
        });

        $.when.apply(undefined, promises).done(function() {

            $('#inner').fadeIn(1000, function() {
                $("#loading").hide();
            });

        });
    });
}
like image 158
adeneo Avatar answered Oct 06 '22 00:10

adeneo