简体   繁体   中英

When loading html with ajax in jQuery, how can I make sure my loading gif remains visible the entire time until the html has been added?

I have an ajax call which loads some HTML into the DOM. If the call was successful I show a spinning loading gif and when the call is complete I hide it. The code:

$.ajax({
    url: someUrl,
    type: 'POST',
    dataType: 'json',
    data: someData,
    success: function(response){
        $(myLoadingGif).show(); // Show the loading gif
        $(myContainer).html(response);
    },
    complete: function(){
        $(myLoadingGif).hide(); // Hide the loading gif. Note: HTML has not been added yet
    }
});

The problem is: The loading gif becomes hidden a couple of seconds BEFORE the HTML is added, even though I declared it in the complete section of the ajax call. I want it to remain visible the entire time. And I don't want to do an ugly setTimeout() of 1000ms just to delay it. I might add that the chunk of HTML loaded is fairly big. It's a table with 20-40 rows.

Any ideas on how to make sure the gif remains visible until the HTML has actually been added?

Success fires every time your ajax call returns a value. Complete fires when the last value is returned from the Ajax call. Because your Ajax call only returns values once, success and complete fire at the same time.

$(myLoadingGif).show();
$.ajax({
    url: someUrl,
    type: 'POST',
    dataType: 'json',
    data: someData,
    success: function(response){
        // Show the loading gif
        $(myContainer).html(response);
        $(myLoadingGif).hide();
    },
    failure: function(){
        $(myLoadingGif).hide();
    }
    complete:function(){}        
});

Try the above and see if this works.

You need yo hide the gif, after the new HTML is attached to the DOM, so because .html() is synchronous, any code put after calling .html() would execute after the new html is appended to the DOM. But sometimes, there's a delay, just because the DOM is added, but the browser engine not render it yet, it's there, but not showing. For that purpuse, try a hack, sometimes it's been usefull to me:

$.ajax({
    url: someUrl,
    type: 'POST',
    dataType: 'json',
    data: someData,
    success: function(response){
        $(myLoadingGif).show(); // Show the loading gif
        $(myContainer).html(response);
    },
    complete: function(){
        setTimeout(function(){$(myLoadingGif).hide();},0);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM