image.onload 和 image.onerror 的无限循环

phu*_*ury 2 javascript

我正在尝试加载和图像,如果 url 无效,则输入错误图像。在我的情况下, onerror 事件似乎被无限调用:

html:

<div id="output"></div>
Run Code Online (Sandbox Code Playgroud)

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');
Run Code Online (Sandbox Code Playgroud)

您会注意到日志显示 'no image at url: image-id'

Ale*_*ler 5

问题是你successUrlonload回调中重复地重新分配,导致无限递归,因为它被一遍又一遍地调用。

要解决,请更新onload回调:

img.onload = function() {
    this.onload = function() {
       // Whatever you want to do now.
    };
    this.src = successUrl;
};
Run Code Online (Sandbox Code Playgroud)

(与错误回调相同)。

一般来说,我不认为这是一种干净的方式。我会简单地创建多个Image对象以避免混淆(并且可能预加载带有页面的微调器)。分配Image只有很小的开销,几乎无关紧要。