te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - <img> onerror with 404 image response - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - <img> onerror with 404 image response - Stack Overflow

programmeradmin3浏览0评论

I'm loading images from a server which returns images when there is a 404. That is, if the image I'm loading doesn't exist, the server will return a 404 response with a 200x200 PNG fallback image that says "photo not available" on it.

I would like to detect the times when this happens client-side. I tried the onerror attribute:

<img src=".jpg" onerror="console.log(this)" />

This code only works when the 404 response from the server has no image at all. Since my 404 response does, the onerror event is never fired.

Is there a way around this problem, short of pre-loading images with JavaScript?

I'm loading images from a server which returns images when there is a 404. That is, if the image I'm loading doesn't exist, the server will return a 404 response with a 200x200 PNG fallback image that says "photo not available" on it.

I would like to detect the times when this happens client-side. I tried the onerror attribute:

<img src="http://example./photo.jpg" onerror="console.log(this)" />

This code only works when the 404 response from the server has no image at all. Since my 404 response does, the onerror event is never fired.

Is there a way around this problem, short of pre-loading images with JavaScript?

Share Improve this question asked Feb 26, 2015 at 20:03 BradBrad 163k55 gold badges377 silver badges552 bronze badges 3
  • If the onerror handler doesn't work, you could do a head request to the url's and check for a 404 – adeneo Commented Feb 26, 2015 at 20:06
  • Pinging the URL inside of JavaScript and checking the response code? – Lloyd Banks Commented Feb 26, 2015 at 20:07
  • Yes, those are options I will resort to if I cannot find a better way. I'd much prefer a different solution so I can leave the images in the markup for non-JavaScript users. – Brad Commented Feb 26, 2015 at 20:10
Add a ment  | 

5 Answers 5

Reset to default 1

One solution is NOT to return an image when the intended image is not found on the server. Instead, the error image is displayed later using the onerror event.

<img src="tttttttt.png" onerror="this.onerror=null;this.src='https://www.google./images/srpr/logo11w.png'" />

JSFiddle

Reference: jQuery/JavaScript to replace broken images

(Updated, as @Brad pointed out the obvious details I was ignorant to.)

I stumbled across this which seems to trigger the onerror() properly:

<html>
    <head>
        <script src="http://code.jquery./jquery-2.1.3.min.js"></script>
        <script type="text/javascript">
        (function($) {
            $.fn.errimg = function(options) {
                return this.each(function() {
                    if (this.tagName.toLowerCase() != 'img')
                        return;         

                    // store current img for error reference
                    var $_orig = $(this);
                    // create "production" image
                    var $newImg = $_orig.clone()
                        .attr('src', $_orig.data('src') || '')
                        .one('error', function() {
                            $(this).parent()
                                .empty()
                                .append($_orig);
                        });
                    // replace current img
                    $_orig.parent().empty().append($newImg);
                });
            };
        })(jQuery);         

        $(function() {
            $('.js_img img').errimg();
        });
        </script>
    </head> 

    <body class="js_img">
        <img id="testimgbad" src="http://img4.homefinder./i/00000000-0000-0000-0000-000000000000/w200-h-q" onerror="console.log('errored out');" />
    </body> 

</html>

The workaround I took is calling an internal method trough ajax that check with a httpclient if the image is returning a 404 premade page. If so (any status 404), then returns my own anonymous image, if not, returns the string itself.

U might use onload function instead of onerror, and check for the image loaded (if you know something about that image at the beginning).

You might as well messure how many times do you expect this to happen, since your're registering some kind of listener for every possible image that might be unnecesary.

If you are sure the dimensions differ between an existing image and a 404-image, you could use that information to do some other trick.

For example you want to the show the biggest 16:9 Youtube thumbnail available. Youtube returns a 120px by 90px '404-image' if the fetched thumbnail does not exist. So let's fetch the maxresdefault thumbnail and show an mqdefault thumbnail as fallback:

<img src="https://img.youtube./vi/{id}/maxresdefault.jpg" onload="if (this.naturalWidth === 120) {this.src = this.currentSrc.replace('maxresdefault', 'mqdefault');}">
发布评论

评论列表(0)

  1. 暂无评论