JQuery - 图像循环等待加载

时间:2014-03-10 02:41:40

标签: javascript jquery

我有以下for循环,可以动态地将图像加载到页面上。对于少量图像,例如10,它的效果很好。除此之外,我开始在加载图像方面遇到问题,远程服务器不堪重负,而不是发送图像(获取红色X而不是图像)。图像是从成像数据库中从服务器发送的,所以不幸的是它很快就会不堪重负。

for (var c = 0; c < b; c++) {
   url = transurl + "&action=getRelatedItem&docid="+ d[c].id +"&side=front";
   img = $("<img />").attr('src', url ).attr('width','600');
   allimages.append(img);
}

在此页面中,allimages是页面上的空div。我想我需要等待图像加载才能继续前进并尝试加载另一个图像,依此类推,但我不知道如何让循环停止并等待图像加载,然后继续前进到下一个?

提前致谢。

1 个答案:

答案 0 :(得分:0)

更新:根据凯文,调整了src分配

我相信你正在寻找一个基本的图像预加载器。我尝试调整您当前的代码,但我认为使用for循环来满足您当前的需求并不会在性能方面保持干净。因此,假设您需要在完成加载后按顺序追加每个图像:

var count = 0; // initial count is 0
allImages.on('insertImg', insertImgFn); // when event insert image is triggered, run insertImgFn

insertImgFn(); // runs the function once to start the loading process  << Edit

function insertImgFn(){
    url = transurl + "&action=getRelatedItem&docid="+ d[count].id +"&side=front";
    img = new Image(); // defines an image object
    $(img).load(function(){ // on image load completion
        var countMatch = count < b; // checks if your count is less than the amount of images
        if(countMatch){
            allImages.append(img); // appends your image
            count++; // increase the count
            allImages.trigger('insertImg'); // triggers the event 
        }// end of if countMatch
    });// end of .load
    img.src = url; // assigns the url to the image object
    $(img).width(600); // sets the width to the image
};// end of insertImgFn
相关问题