javascript - Infinite loop with image.onload and image.onerror - Stack Overflow

I'm trying to load and image and if the url is not valid, put an error image instead. In my case t

I'm trying to load and image and if the url is not valid, put an error image instead. In my case the onerror event seem to be called infinitely:

html:

<div id="output"></div>

javascript:

function createImage(imageId) {
    var spinnerUrl = ';text=spinner';
    var errorUrl = ';text=error';
    var successUrl = ';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');

you'll notice that the log displays 'no image at url: image-id'

I'm trying to load and image and if the url is not valid, put an error image instead. In my case the onerror event seem to be called infinitely:

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./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');

you'll notice that the log displays 'no image at url: image-id'

Share Improve this question edited Jul 11, 2014 at 14:03 phury asked Jul 11, 2014 at 13:43 phuryphury 2,2132 gold badges24 silver badges34 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

The problem is that you re-assign the successUrl repeatedly in your onload callback, causing infinite recursion because it gets called over and over again.

To solve, update the onload callbacks:

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

(The same with the error callback).

In general, I don't think this is a clean way of doing it. I would simply create multiple Image objects to avoid confusion (and possibly preload the spinner with the page). Allocating Image has only tiny overhead and almost never matters.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745286447a4620592.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信