我正在使用 JavaScript 加载图像。像这样:
images[0]=new Image();
images[0].onload=function(){loaded++;console.log(loaded)};
images[0].src="assets/img/image.png";
当我查看日志时,我发现所有图像都加载得很好,因为“loaded”变量的值随着每个加载图像的增加而增加。
但是我想停止执行任何进一步的操作,直到这个数量达到最大值,所以在设置图像之后,我放置了一个 while 循环。
while(loaded<11){
document.getElementById("test").innerHTML="Loading "+loaded+"/11";
console.log(loaded);
}
//Some code here which should only run after everything has been loaded
//In other words: when the statement in the while cycle becomes false
但是我的浏览器只是崩溃了,因为 while 似乎陷入了无限循环。当我检查日志时,我看到“0”被写入了 1000 次,之后是从 1 到 11 的数字(这意味着图像实际上已加载,但 while 不关心它,并且崩溃得更快比它可能发生的)。
我认为我在这里尝试使用的方法不是解决此问题的正确方法。
在加载网站所需的每项 Assets 之前,我如何才能暂停一切?
最佳答案
使用 promises 和异步函数,有一个很好的方法可以等待所有图像加载完毕(没有回调,没有加载图像计数):
async function loadImages(imageUrlArray) {
const promiseArray = []; // create an array for promises
const imageArray = []; // array for the images
for (let imageUrl of imageUrlArray) {
promiseArray.push(new Promise(resolve => {
const img = new Image();
// if you don't need to do anything when the image loads,
// then you can just write img.onload = resolve;
img.onload = function() {
// do stuff with the image if necessary
// resolve the promise, indicating that the image has been loaded
resolve();
};
img.src = imageUrl;
imageArray.push(img);
}));
}
await Promise.all(promiseArray); // wait for all the images to be loaded
console.log("all images loaded");
return imageArray;
}
或者您可以等待单个图像加载:
async function loadImage(imageUrl) {
let img;
const imageLoadPromise = new Promise(resolve => {
img = new Image();
img.onload = resolve;
img.src = imageUrl;
});
await imageLoadPromise;
console.log("image loaded");
return img;
}
您可以像这样使用它(使用 promise 链):
loadImages(myImages).then(images => {
// the loaded images are in the images array
})
或者在异步函数中:
const images = await loadImages(myImages);
关于javascript - 在 JavaScript 中等待图像加载完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37854355/