问题
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:
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];
}
来源:https://stackoverflow.com/questions/3862879/preload-an-array-of-images-with-jquery