If I use jQuery to set the background image of the page like so:
$('body').css({
"background-image": 'url(' + myImageUrl + ')'
});
How can I detect and handle HTTP errors (500, 503, 404, etc) that might be returned from the image URL?
I did find a jQuery .error()
method that registers a callback, but it's marked as deprecated in 1.8 with no indication of what is supposed to replace it. (I also can't seem to get it to work, deprecated or not.)
Based on the comments and the answer below I tried this variation and it seems to work, but the answer is getting down-votes. Is there a reason this is bad?
$('<img>').error(function(obj) {
alert('error');
}).load(function() {
$('body').css({
"background-image": 'url(' + myImageUrl + ')'
});
}).attr('src', myImageUrl);
Try this
jQuery
Live Demo
JavaScript: