答案很好,但它引入了一个问题。无论您何时分配onload
或onerror
直接分配,它都可以替换之前分配的回调。这就是为什么有一个不错的方法可以像在MDN 上所说的那样“在指定的侦听器上注册指定的侦听器”。您可以在同一事件上注册任意数量的侦听器。
让我重写一下答案。
function testImage(url) {
var tester = new Image();
tester.addEventListener('load', imageFound);
tester.addEventListener('error', imageNotFound);
tester.src = url;
}
function imageFound() {
alert('That image is found and loaded');
}
function imageNotFound() {
alert('That image was not found.');
}
testImage("http://foo.com/bar.jpg");
由于外部资源加载过程是异步的,因此最好使用带有承诺的现代JavaScript,如下所示。
function testImage(url) {
// Define the promise
const imgPromise = new Promise(function imgPromise(resolve, reject) {
// Create the image
const imgElement = new Image();
// When image is loaded, resolve the promise
imgElement.addEventListener('load', function imgOnLoad() {
resolve(this);
});
// When there's an error during load, reject the promise
imgElement.addEventListener('error', function imgOnError() {
reject();
})
// Assign URL
imgElement.src = url;
});
return imgPromise;
}
testImage("http://foo.com/bar.jpg").then(
function fulfilled(img) {
console.log('That image is found and loaded', img);
},
function rejected() {
console.log('That image was not found');
}
);