views:

35

answers:

1

Hi all.

I am using jQuery to build an array of images from a php array. I want to loop through these images, preloading them while displaying a little loading gif until all of the images are loaded.

At the moment, I have tried many methods of doing so and the rest of the page always seems to carry on loading and so the images are being preloaded, but not before the page loads the rest of the content.

Here is what I have:

 <script type="text/javascript">

  // Get list of images and build array + set vars

  var imgArray = new Array;
  var imgCount = <?php echo count($files); ?>;
  var imgNum = <?php echo $rand; ?>;
  var imgDir = "<?php echo $dir; ?>";
  var imgBlurDir = "<?php echo $blurdir; ?>";


 $(document).ready(function() {

  <?php
   for ($i=0;$i<count($files);$i++) {
    echo "imgArray[$i]='" . $files[$i] . " ' ; \n";
   }
  ?>


  // Preload Images:
  $('mainImg #orig').html('<img src="images/preload.gif" style="position: relative; top: 310px;" />');
  for(i=0; i<imgCount; i++) { 
   $('<img>').attr("src", imgDir+imgArray[i]).load(function() { $('.profile').append( $(this) )});
   $('<img>').attr("src", imgBlurDir+imgArray[i]).load(function() { $('.profile').append( $(this) )});
  }

  // ^^^^ this doesnt work yet...

  $('#mainImg #orig').html("<img src='"+imgDir+imgArray[imgNum]+"' />").delay(10).fadeIn(1000);
 });

</script>

As you can see, #orig is set to display the preload.gif, then images should be pre-loaded, then #orig should change and fade in the image that is currently selected in the array. This does not happen, i never see the gif and the images carry on loading for a while after the page is loading.

Please advise, Many thanks in advance!

+1  A: 

You are creating a sting and inserting it into the document, where it should become a part of DOM. What you need to do is create a JS Image object, somewhat like this:

// Preload Images:
for(i=0; i<imgCount; i++) { 
  var image_preload = new Image();
  image_preload.src = imgDir+imgArray[i];
}
Piskvor
Thanks for the quick reply. This works I can see the images loading, however the rest of the page is still loading up while the images are loading?
Lunarben
@Lunarben: As the code block is inside ` $(document).ready`, it gets invoked as soon as the DOM is loaded - that is, some parts of the page can still be loading (other images, stylesheets IIRC, etc).
Piskvor
I didn't think of that! seems to be working fine now. Thank you very much! :)
Lunarben