我有以下 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。我认为我需要等待图像加载,然后再继续并尝试加载另一个图像,依此类推,但我不确定如何要求循环停止并等待图像加载,然后再继续下一个?
提前致谢。
最佳答案
更新:根据 Kevin 的说法,调整了 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
关于javascript - JQuery - 图像循环等待加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22291230/