switchstatement (switchstatement) wrote in 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) {
                    //i've tried timeouts here, but it's imprecise

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


    default userpic

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.