我正在循环加载 8 个图像,我想暂停每个图像的循环以等待其加载。所以不是:
image = new Image()
image.onload = function(){ /*do anything*/ }
image.src = "abc.svg"
我想要这样的东西:
image = new Image()
image.src = "abc.svg"
image.waitLoad()
//do anything
有没有办法使用 Javascript 做到这一点? 提前致谢。
最佳答案
你不能暂停。但是,您可以延迟下一个图像加载,直到加载上一个图像。例如:
var images = ['path1', 'path2', 'path3', 'path4'];
(function next(images) {
if (images.length) {
var img = new Image();
img.onload = function() { next(images); };
img.src = images.shift();
}
})(images.slice());
在这种情况下,它只会在获取上一张图像后加载下一张图像。如果图像 src 有可能被破坏,请确保你也处理了,例如img.onload = img.onerror = function() { 下一步(图片); };
.
var images = [1, 2, 3, 4];
(function next(images) {
if (images.length) {
var img = new Image();
img.onload = function() {
document.body.appendChild(img);
setTimeout(function() { next(images); }, 500);
};
img.src = images.shift();
}
})(images.slice());
<base href="http://lorempixel.com/100/100/food/">
关于JavaScript:加载图像后继续执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32951547/