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 badges1 Answer
Reset to default 6The 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.