[英]Infinite loop with image.onload and image.onerror
我正在嘗試加載圖像,如果URL無效,請放置錯誤圖像。 就我而言,onerror事件似乎被無限調用:
的HTML:
<div id="output"></div>
javascript:
function createImage(imageId) {
var spinnerUrl = 'http://placehold.it/600&text=spinner';
var errorUrl = 'http://placehold.it/600&text=error';
var successUrl = 'http://placehold.com/600&text=success';
var img = new Image();
img.onerror = function() {
console.log('no image at url: ' + imageId);
this.src = errorUrl;
};
img.onload = function() {
this.src = successUrl;
};
img.src = spinnerUrl;
return img;
};
function loadImage(id) {
document.getElementById(id).appendChild(createImage('image-id'));
};
loadImage('output');
您會注意到該日志顯示“ URL:image-id處沒有圖像”
問題是您在onload
回調中重復地重新分配了successUrl
,導致無限遞歸,因為它被一遍又一遍地調用。
要解決,請更新onload
回調:
img.onload = function() {
this.onload = function() {
// Whatever you want to do now.
};
this.src = successUrl;
};
(與錯誤回調相同)。
總的來說,我認為這不是一種干凈的方法。 我將簡單地創建多個Image
對象以避免混淆(並可能在微調器中預加載頁面)。 分配Image
只有很小的開銷,幾乎沒有關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.