Can I catch http errors when using jQuery to modif

2019-08-17 16:16发布

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);

1条回答
Juvenile、少年°
2楼-- · 2019-08-17 16:37

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;
查看更多
登录 后发表回答