0

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);
2
  • .error() would not catch that anyway. Only way to make sure would to preload the image and see if it loads. After that apply it to the bg image. Commented Sep 3, 2013 at 13:27
  • you could always make a ajax request to check first but that would create possible overhead. Commented Sep 3, 2013 at 13:27

1 Answer 1

0

Try this

jQuery

Live Demo

var $image = $("<img />");
$image.on("error",function() { 
  $('body').css({
    "background-image": 'url(defaultimage.jpg)'
  });
}).on("load",function() {
  $('body').css({
    "background-image": 'url(' + myImageUrl + ')'
  });
}).attr("src",myImageUrl);

JavaScript:

var image = new Image();
image.onerror=function() { 
  document.body.style.backgroundImage="url(defaultimage.jpg)"
}
image.onload=function() {
  document.body.style.backgroundImage="url("+myImageUrl+")"
}
image.src=myImageUrl;
Sign up to request clarification or add additional context in comments.

2 Comments

No idea why the down-votes. It's a sound idea imo. The only downside is loading the image twice, which should be minimal impact considering caching. I don't need the default image bit, but it's a nice touch. Thanks.
Great - Yes, the image should come from cache

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.