switchstatement (switchstatement) wrote in javascript,
switchstatement
switchstatement
javascript

jquery, ajax, and waiting until data is fully loaded

We have this little image gallery thing built with jquery. It fetches a page that selects some random images and writes some html, then updates the html in the image gallery container. It's supposed to work like this:

- button clicked
- fetch page
- data received
- old stuff fades out
- new stuff fades in

The images loaded are really big (they're coming from a photographer and we have no control over the file size), so what's happening is the "new stuff fades in," event is occurring while the images are still loading, and it looks kind of dumb. This is a simplified version that just loads one random image:

    <script type="text/javascript">
    $(document).ready(function() {
        $("#nextButton").click(function() {
            $('#an_image').fadeOut('fast', function() {
                $.get('./image_swap.php?n=1&node=117', function(data) {
                    $('#an_image').html(data);
                    //i've tried timeouts here, but it's imprecise
                    $('#an_image').fadeIn("slow");
                });
            });
        });
    });


I've tried rearranging the nesting, thinking putting everything else under $.get('./image_swap.php?n=1&node=117', function(data) {...} would cause the callbacks to not happen until the data was loaded, but it's somehow even worse that way.

Is there a way to have jquery fetch the new page and not do anything else until the contents (specifically, the images) have fully loaded? Given their size and number, pre-loading the images in the background isn't really an option.
  • Post a new comment

    Error

    default userpic

    Your IP address will be recorded 

  • 4 comments
You can use the jquery "load" event on images:

http://api.jquery.com/load-event/
here is what I do to ensure things are loaded completely across all browsers:
jQuery(window).load(function(){
  if (jQuery.browser.safari && document.readyState != 'complete'){
    // chrome / safari will trigger load function before images are finished
    // check readystate in safari browser to ensure images are done loading
    setTimeout( arguments.callee, 100 );
    return;
  }
  // do things you want to do
});
Hi there, awesome site. I thought the topics you posted on were very interesting

Thanks for posting, I like this blog!