最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论