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.
我正在使用jQuery从php数组构建一个图像数组。我想循环遍历这些图像,在显示一个小加载gif的同时预加载它们,直到所有的图像都被加载。
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.
如您所见,#orig被设置为显示预加载。gif,然后图像应该被预加载,然后#orig应该在当前数组中选择的图像中改变和消失。这不会发生,我从来没有看到gif和图片在加载一段时间后加载。
Please advise, Many thanks in advance!
请告知,非常感谢!
1 个解决方案
#1
6
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:
您正在创建一个sting并将其插入到文档中,在文档中它应该成为DOM的一部分。您需要做的是创建一个JS图像对象,有点像这样:
// Preload Images:
for(i=0; i<imgCount; i++) {
var image_preload = new Image();
image_preload.src = imgDir+imgArray[i];
}
#1
6
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:
您正在创建一个sting并将其插入到文档中,在文档中它应该成为DOM的一部分。您需要做的是创建一个JS图像对象,有点像这样:
// Preload Images:
for(i=0; i<imgCount; i++) {
var image_preload = new Image();
image_preload.src = imgDir+imgArray[i];
}