psorensen
psorensen

Reputation: 827

jQuery .load() callback firing early

I created to following code to retrieve search results via load(). The trouble I'm having is that the callback function of the load fires before the ajaxed results are on the DOM. Sometimes the timing seems right, but often it's up to a second early.

  // assign area to load content
  var mainContent = $("#ajaxContent");

  // on form change
  $('#facets').change(function(e){

    // serialize form data
    var formData = $("#facets").serialize();

    // fade in loading animation while fade out page
    $('#preload').fadeIn();
    $('.wrap').fadeTo("fast", 0.33);

    // ajax search results, on callback fade out animation, fade in page
    mainContent.load('?' + formData + ' #ajaxContent', function(){
       $('.wrap').fadeTo("fast", 1);
       $('#preload').fadeOut();
    });

    e.preventDefault();
  });

Any obvious mistakes? Thanks!

Upvotes: 0

Views: 619

Answers (2)

Kevin B
Kevin B

Reputation: 95028

The best case here would be to start the ajax request immediately, then showing the preloader. when the ajax is finished, stop fading in the preloader and show the wrap.

$('.wrap').fadeTo('fast', 0.33);
$('#preload').fadeIn();
$.get('?' + formData).done(function (html) {
    $('<div>').html(html).find('#ajaxContent').appendTo(mainContent);
}).always(function () {
    $('#preload').stop().fadeOut();
    $('.wrap').stop().fadeTo('fast', 1);
});

this results in requesting and showing the content as fast as possible, while still having the preloader if it takes long enough for it to show.

Guess you could also still use .load for this:

$('.wrap').fadeTo('fast', 0.33);
$('#preload').fadeIn();
mainContent.load('?' + formData + ' #ajaxContent', function () {
    $('#preload').stop().fadeOut();
    $('.wrap').stop().fadeTo('fast', 1);
});

Upvotes: 1

akatakritos
akatakritos

Reputation: 9858

Sounds like you want to fadeIn the loading indicator, load the content, then fade it back out. But as you have written, you are starting a fadeIn animation and an asynchronous load at the same time. Which finishes first is anyone's guess.

fadeIn takes a call back to run when the animiation is finished. Trigger your ajax load inside that callback:

$('.wrap').fadeTo("fast", 0.33);
$('#preload').fadeIn(function() {

    // ajax search results, on callback fade out animation, fade in page
    mainContent.load('?' + formData + ' #ajaxContent', function(){
       $('.wrap').fadeTo("fast", 1);
       $('#preload').fadeOut();
    });
});

This will make things happen in the order you want.

Upvotes: 1

Related Questions