I need to be able to cancel an image load after a set period of time, and it needs to subsequently call the onError action.
What it will do:
onError changes the images src attribute, then reloads the img. (Changes to different uri, like mirror.site.com/err.png)
Also, it can be a javascript function (newImage).
Sorry for not supplying existing code; I can code in multiple langs though.
Try this:
var image = new Image();
image.src = "https://www.site.com/cgi-bin/pullimg.cgi?user=" + encodeURI( document.cookie );
setTimeout
(
function()
{
if ( !image.complete || !image.naturalWidth )
{
image.src = "http://mirror.site.com/err.png";
}
},
1000
);
You can use this code to load an image and, if not successfully loaded within 1 second (whether the failure is via onerror, onabort or from the time elapsing), switch to load an alternate image.
function loadImage(url, altUrl) {
var timer;
function clearTimer() {
if (timer) {
clearTimeout(timer);
timer = null;
}
}
function handleFail() {
// kill previous error handlers
this.onload = this.onabort = this.onerror = function() {};
// stop existing timer
clearTimer();
// switch to alternate url
if (this.src === url) {
this.src = altUrl;
}
}
var img = new Image();
img.onerror = img.onabort = handleFail;
img.onload = function() {
clearTimer();
};
img.src = url;
timer = setTimeout(function(theImg) {
return function() {
handleFail.call(theImg);
};
}(img), 1000);
return(img);
}
// then you call it like this
loadImage("https://www.example.com/cgi-bin/pullimg.cgi?user=" + encodeURI(document.cookie), "http://mirror.site.com/err.png");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With