逐步加载和附加图像 [英] Loading and appending images progressively
问题描述
我有一个无法解决的问题.我制作了一个简单的jQuery相册图库,并具有以下功能:
I have an issue I can't get over. I made a simple jQuery album gallery and I have this function:
function loadAlbum (index) {
for (var j=1; j < xmlData[index].length; j++) {
var img = new Image();
$(img).load(function() {
$(this).hide();
$('#album'+index+' .photoContainer').append(this);
$(this).fadeIn();
})
.error(function(){
//alert("Could not load one or more photo!");
})
.attr({
'src': xmlData[index][j],
'id': 'img'+index+j,
'class': 'photoFrame',
'width': newW,
'height': newH
})
.css({
'width': newW,
'height': newH
});
};
};
现在,您可以看到src的所有图像都是从包含数据的外部XML文件中导入的(图像名称是渐进式的ex.:photo001.jpg、photo002.jpg等).
Now, as you can see all the images src's are imported from an external XML file containing the data (images names are progressive ex.:photo001.jpg, photo002.jpg and so on).
它们在DOM的for循环中创建,并附加到div.
They are created in the DOM trough a for loop and appended to a div.
您可能会说什么?我需要按照XML数据上指定的方式以渐进方式附加所有图像,但这仅在本地计算机上发生,如果在某些服务器上载则不会发生.我发现这是由于每个图像的加载时间取决于大小而导致的...但是我仍然不知道如何解决此问题.有人知道吗?
What's the issue you may say ? I need all images to be appended in a progressive way as specified on the XML data but this happens only on the local computer and not if uploaded on some server. I figure out that this is due to the different loading time of each image depending on size... but I still can't figure out how to work this around. Does anyone have any idea?
推荐答案
以下尝试一次加载一张图像.加载图像后,将随后加载集合中的下一个图像.
The following attempts to load one image at a time. Once an image is loaded, the next in the set is loaded afterward.
function loadAlbum(index) {
var i = 0;
var j = xmlData[index].length;
function loadImage() {
if (i >= j) return;
// do what you're doing in the loop except for ....
$(img).load(function() {
$(this).hide();
$('#album'+index+' .photoContainer').append(this);
$(this).fadeIn();
// increments i by 1 and calls loadImage for the next image.
i++;
loadImage();
// etc.
}
loadImage();
}
我将它作为练习,让您确定如何一次加载多张图像并仍然保持顺序:)
I leave it as an exercise for you to determine how multiple images can be loaded at once and still maintain the ordering :)
这篇关于逐步加载和附加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!