Preload an array of images using jquery

I am using jQuery to create an array of images from a php array. I want to skip these images by pre-loading them, showing a small gif loading until all the images have been downloaded.

At the moment, I tried many ways to do this, and the rest of the page always loads, so the images are 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>

, #orig preload.gif, , #orig , . , gif, .

, , !

+5
1

, DOM. , JS, :

// Preload Images:
for(i=0; i<imgCount; i++) { 
  var image_preload = new Image();
  image_preload.src = imgDir+imgArray[i];
}
+6

All Articles