1

我有一个显示高质量图片的页面。图片通常需要一段时间才能加载。我有一个在加载图片时运行的 jQuery 函数#image我希望这个函数按照它们出现的顺序一次预加载其他图像 1。

所以:如果我在第一张图片上,它应该加载图片1并显示它,然后在pic1完成后预加载/缓存第二张图片。正在加载的图片都已经附加了一个缓存头。当 pic2 完成加载后, pic3 应该开始加载。如果您想知道,我有一个 cgi 后端,可以循环打印东西等。

到目前为止,我有以下工作:

$('#image').load(function() {
 preLoad2 = new Image()
 preLoad2.src = "pic2"
})

然后,我可以使用同一$('#image').load(function() { }行的另一个函数继续此操作,但是我该如何制作才能使下一张图片在完全加载之前不会开始加载。我宁愿不使用定时延迟,因为这不是很准确。

这是我目前所拥有的。我在这个例子中使用了一个 bash cgi 脚本。

#set a loop counter
# variables will be refered to as $[var-name]
count=1
first=true
#loop through all images that need pre-loading
for file in *
  do
    #check if the picture matches the search criteria
    if [[ "$file" = *$lowerSearch* ]]
      then
        #create a js script
        echo "<script language=\"javascript\" type=\"text/javascript\">"
        echo "function load$count() {"
        echo " preLoad$count = new Image()"
        echo " preLoad$count.src = \"?loadFile=$file\""
        echo "}"
        #the first one of these functions should be bound to the main image load event
        if [ "$first" = 'true' ]
          then
            echo "document.getElementById('image').onload = load$count()"
        #the 2nd and on should be bound to the pre-load of the previous picture
        else
          echo " preLoad$last.onload = load$count()"
        #end if
        fi
        echo "</script>"
        #store the current count so that the next time through it can be used to call the last loaded picture
        last=$count
        first=false
        #add 1 to count
        count=$((count+1))
    #end if
    fi
#end loop
done

这是如何工作的:循环浏览图片。如果图片符合搜索条件,则运行主代码...否则跳过循环。在搜索条件中,它创建一个包含函数的 js 脚本。该函数加载循环当前引用的图片。然后它创建一个 onLoad 函数,该函数引用最后一张预加载的图片,并为其设置一个 onLoad 事件,以运行刚刚创建的函数。

我相信这个问题的答案与这个问题有些相关

4

3 回答 3

1

First create JSON record of images like this

var imageRecord = ['image1.jpg',
                'image2.jpg',
                'image3.jpg',
                'image4.jpg',
                'image5.jpg'];

then create function to load image one after another

function loadAllImages(index){
  if( index >= imageRecord.length ){
    return;
  }
  //create image object
  var image = new Image();

  //add image path
  image.src = imageRecord[index];

  //bind load event
  image.onload = function(){
    //now load next image
    loadAllImages(index + 1);
  }

}

hope this small snippet will help you.

to understand whole concept of preload images using javascript, please visit http://zainultutorials.blogspot.in/2013/11/preload-images-using-javascript.html

于 2013-11-20T13:35:24.413 回答
0

如果你有图像的url数组,你可以做这样的事情:demo

<div id="cont"></div>
<script type="text/javascript">
function loadImagesInSequence(images) {
  if (!images.length) {
    return;
  }

  var img = new Image();

    //Remove if from the array list and return it to the variable
    var url = images.shift();

  img.onload = function(){ loadImagesInSequence(images) };
  img.src = url;

    $("#cont").append(img);
}

loadImagesInSequence(['http://www.nasa.gov/centers/goddard/images/content/433226main_Misti_ComaCluster.jpg',
'http://www.hdwallpapers.in/walls/cold_universe-wide.jpg',                     'http://scienceblogs.com/startswithabang/files/2013/05/chemical_composition_universe.jpeg']);
</script>

或者,如果您的页面中有图像标签,您可以使用以下内容:demo

<img id="img1" src="http://miniontours.yzi.me/loading.gif" data-image="http://www.nasa.gov/centers/goddard/images/content/433226main_Misti_ComaCluster.jpg" />

<img id="img2" src="http://miniontours.yzi.me/loading.gif" data-image="http://www.hdwallpapers.in/walls/cold_universe-wide.jpg" />

<img id="img3" src="http://miniontours.yzi.me/loading.gif" data-image="http://scienceblogs.com/startswithabang/files/2013/05/chemical_composition_universe.jpeg" />
<script type="text/javascript">
var imgs = [];
$("img").each(function(){
    imgs.push({
        "ID": this.id,
        "src" : $(this).data("image")
              });
});


loadImagesInSequence(imgs);

function loadImagesInSequence(images) {
    if (!images.length) {
        return;
      }

  var img = images.shift();
  var url = img.src;

  img = $("#"+img.ID);
  img.load(function(){ loadImagesInSequence(images); });
  img.attr("src",url);
}
</script>
于 2013-11-14T03:34:34.977 回答
0

在过去,我使用过类似于此图像预加载器的东西:

http://www.webreference.com/programming/javascript/gr/column3/index.html

代码的格式很奇怪,但代码本身很好。设置 ImagePreloader “类”后,我使用了这样的方法:

function preloadImages(imageSRCs){
var loadingMessage = $('<div/>').addClass('loading').html('<h1>LOADING</h1>');

// stay classy: tell the user you're loading images
$('#content').append(loadingMessage);

// this imgPreloader takes care of loading the images
imgPreloader = new ImagePreloader(imageSRCs, function(imgArr, numLoaded){
    if(this.nImages == numLoaded){
        loadingMessage.remove();
        //do whatever you want with the images here
        for(var i = 0; i < imgArr.length; i++){
            var pathIdPattern = new RegExp("[^/]+\\.");
            var imgName = pathIdPattern.exec(imgArr[i].src)[0];
            var imgId = imgName.substring(0, imgName.length-1);
            $('div#images').append($(imgArr[i]).hide().attr("id", imgId));
        }
    }else{
        loadingMessage.text('Sorry, there was a problem loading the site : / ');
        console.error("Only " + numLoaded + " of " + this.nImages + " images loaded successfully.");
    }
});}

其中 imageSRCs 参数只是图像路径的字符串数组。也许这是您正在寻找的更复杂的解决方案,但我希望它有所帮助!

于 2013-11-14T03:26:46.100 回答