这里我有一个简单的测试代码,可以在浏览器中加载图像测试。这里我使用异步onload事件在完成加载后将图像添加到dom。图像加载得很好。问题是如果我连续重新加载页面多次图像序列更改。如果在图像1之前加载图像2,有时图像3首先加载,等等。我如何制作确保图像按顺序加载,比如第一次加载图像1,然后是每次加载页面时图像2,图像3等。我能做到这一点吗?
var images = ['cat1.png','cat2.jpg','cat3.jpg'];
var i = 0;
images.forEach(function(elem,index,arr){
var image=new Image();
image.onload = function(){
document.body.appendChild(image);
console.log(++i);
};
image.onerror = function(){
console.log('error occured');
}
image.src = elem;
image.style.width = '300px';
image.style.height = '300px';
});
答案 0 :(得分:4)
您应该等待onload
事件中的回调。
如果已解雇,您可以迭代并加载下一张图片。
这样可以确保以正确的顺序加载图像(如 array 中所示)。
var images = [
'http://d39kbiy71leyho.cloudfront.net/wp-content/uploads/2016/05/09170020/cats-politics-TN.jpg',
'error',
'https://s2.graphiq.com/sites/default/files/stories/t2/tiny_cat_12573_8950.jpg',
'http://www.bharatint.com/img/categories/our-cat-shop-image.png'
], i = 0;
function loadImageArrayAsync(){
var image = new Image();
image.onload = function(){
document.body.appendChild(image);
if (i++ < images.length - 1) loadImageArrayAsync();
};
image.onerror = function(){
if (i++ < images.length - 1) loadImageArrayAsync();
}
image.src = images[i];
image.style.height = '300px';
image.style.width = '300px';
}
loadImageArrayAsync();
答案 1 :(得分:0)
这是另一种方法。它会在循环中触发所有图像请求,然后在收到响应时会进行一些处理以确定可以显示哪些图像。这样,在请求下一个图像之前,您不必等待一个图像完成加载。代码可能可以完成整理,但你明白了......
var urls = ["/Content/images/Chrysanthemum.jpg", "/Content/images/Desert.jpg", "/Content/images/Hydwewrangeas.jpg", "/Content/images/Jellyfish.jpg", "/Content/images/Koala.jpg"]
var numImages = urls.length;
var images = [numImages];
var gotResponse = [numImages];
var maxDisplayed = -1;
function checkImages(index) {
// Check if previous images have been displayed
if (maxDisplayed == index - 1) {
for (i = index; i <= numImages; i++) {
// Check if we've received a response for this image
if (gotResponse[i] !== true) {
break;
}
maxDisplayed = i;
if (images[i] != null) {
console.log('Adding image ' + i);
document.body.appendChild(images[i]);
}
}
}
}
function imageError(index) {
console.log('Error loading image ' + index);
images[index] = null;
gotResponse[index] = true;
checkImages(index);
}
function imageLoaded(index, image) {
console.log('Loaded image ' + index);
images[index] = image;
gotResponse[index] = true;
checkImages(index);
}
function loadImages() {
$.each(urls, function(index, value) {
var image = new Image();
image.onload = function () {
imageLoaded(index, image);
}
image.onerror = function () {
imageError(index);
}
image.src = value;
image.style.width = '300px';
image.style.height = '300px';
});
}
loadImages();
示例输出:
Error loading image 2
Loaded image 3
Loaded image 0
Adding image 0
Loaded image 1
Adding image 1
Adding image 3
Loaded image 4
Adding image 4