用jQuery预加载图像数组 [英] preload an array of images with jquery

查看:93
本文介绍了用jQuery预加载图像数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery从php数组构建图像数组.我想遍历这些图像,在显示一些加载gif的同时预加载它们,直到所有图像都加载完毕.

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.

这就是我所拥有的:

 <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图像和图像会继续加载一段时间.

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!

推荐答案

您正在创建一个字符串并将其插入到文档中,该文档应成为DOM的一部分.您需要做的是创建一个JS Image对象,如下所示:

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];
}

这篇关于用jQuery预加载图像数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆