最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

function - Detect 404 with javascript - Stack Overflow

programmeradmin2浏览0评论

I'm currently using this JavaScript function to load an image into a div.

function loadImage(id) {
    var image = document.getElementById("image");
    image.src = "/"+id+".png";
    var image = document.getElementById("image");
    image.onload = function () {
            // Do stuff
    };
}

However, how can I do something if the image URL throws back a 404 error?

I'm currently using this JavaScript function to load an image into a div.

function loadImage(id) {
    var image = document.getElementById("image");
    image.src = "http://test./"+id+".png";
    var image = document.getElementById("image");
    image.onload = function () {
            // Do stuff
    };
}

However, how can I do something if the image URL throws back a 404 error?

Share Improve this question asked Dec 25, 2013 at 16:26 user2898075user2898075 791 gold badge3 silver badges10 bronze badges 1
  • Possible duplicate. See stackoverflow./questions/3019077/… and stackoverflow./questions/92720/… – Garett Commented Dec 25, 2013 at 16:38
Add a ment  | 

1 Answer 1

Reset to default 4

You can use onerror.

I am not sure if it reacts also on images as a 404 page, or on bad images only. In both cases, it will likely do what you need.

Alternatively, you can try using AJAX (e.g. XMLHttpRequest or its abstraction), which allows you to handle error codes. Cross-origin restrictions will apply, though. It may be also an overkill.

发布评论

评论列表(0)

  1. 暂无评论