答案是好的,但它引入了一個問題。只要您直接指定onload
或onerror
,它可能會替換先前分配的回調。這就是爲什麼有一個很好的方法,「將指定的偵聽器註冊到它在MDN上說的」上調用的EventTarget「上。您可以在同一個事件中根據需要註冊許多聽衆。
讓我稍微改寫一下答案。
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');
}
);
這可以幫助你:http://stackoverflow.com/questions/1977871/check-if-an-image-is-loaded-no-errors -in-javascript(它是jQuery,但它仍然可能導致你在正確的路徑) – 2012-03-22 03:02:48
嘗試其中一個https://www.google.com/search?rlz=1C1CHJL_esMX444MX444&sourceid=chrome&ie=UTF-8&q=Detect+when+一個+圖像+失敗+到+負載+在+的Javascript#HL = EN&RLZ = 1C1CHJL_esMX444MX444&sclient = PSY-AB&q =站點%3Ahttp%3A%2F%2Fstackoverflow.com + +當檢測+的+圖像+失敗+至+負載+在+的Javascript和OQ =網站: HTTP%3A%2F%2Fstackoverflow.com + + +的圖像+失敗+到+負載在+ +的Javascript&水溶液= F&AQI =&AQL =&gs_l = serp.12當檢測+ ...4485l10141l0l11322l11l9l0l0l0l0l165l703l8j1l9l0.frgbld。與PBX = 1&BAV = on.2,or.r_gc.r_pw.r_qf,cf.osb&計劃生育= 19d0ebe5924d5495&BIW = 1024&波黑= 653 – ajax333221 2012-03-22 03:08:18
滑稽@ ajax333221過這個問題,首先在你的鏈接的結果:) – 2013-11-07 22:35:27