javascript 加载前检查图像是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29991834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:26:46  来源:igfitidea点击:

Check if image exists before loading

javascriptjqueryimagepreloadimage-preloader

提问by Omar Elawady

I've used examples from various other Stack Overflow questions and for some reason this is not working for me. I made a function to get thumbnail images and return either the actual image path or the path to the default (no thumbnail) image.

我使用了来自其他各种 Stack Overflow 问题的示例,但出于某种原因,这对我不起作用。我做了一个函数来获取缩略图并返回实际图像路径或默认(无缩略图)图像的路径。

Using both the JQuery approach as well as the Javascript Image class, I get 404 errors regarding missing images in console and the found images don't error but don't show up. Can anyone perhaps point out what I am doing incorrect?

使用 JQuery 方法和 Javascript Image 类,我收到有关控制台中丢失图像的 404 错误,并且找到的图像没有错误但不显示。谁能指出我做错了什么?

In the getThumbnail() function the "image_url" when written to console appears correct. When I am in the calling function and log the returned value, it just appears as "undefined".

在 getThumbnail() 函数中,写入控制台时的“image_url”显示正确。当我在调用函数中并记录返回值时,它只是显示为“未定义”。

JQuery:

查询:

function getThumbnail(name)
{
    var image_url = "images/" + name + ".jpg";

    $.get(image_url)
        .done(function()
        {
            return image_url;
        })
        .fail(function()
        {
            return "images/default.jpg";
        })
}

Javascript:

Javascript:

function getThumbnail(name)
{
    var image = new Image();
    image.src = image_url;

    image.onload = function()
    {
        return image;
    }
    image.onerror = function()
    {
        return "images/default.jpg";
    }
}

Calling Function:

调用函数:

            $.each( cycle, function( key, value )
            {
                var mapIndex = key;
                var mapValue = value;

                var brick = "<div class='brick small'><a class='delete' href='#'>&times;</a><img src='" + getThumbnail(value) + "' /><h2><span>" + value + "</span></h2></div>";
                $( ".gridly" ).append( brick );
            });

回答by Surely

The problem it does not work is getThumbnail() method will not behave as you want.

它不起作用的问题是 getThumbnail() 方法不会像您想要的那样工作。

The .onload is an async call and for this case, getThumbnail(value) will always have undefined returned result;

.onload 是一个异步调用,在这种情况下, getThumbnail(value) 将始终有未定义的返回结果;

To accomplish what you want, you can do something like:

要完成您想要的操作,您可以执行以下操作:

<img src="/image/..." onerror="javascript:this.src='images/default.jpg'"/>

回答by Omar Elawady

this's not working because returnis in onerrorand onloadfunctions, and because the request is async so function won't wait until the reuest is done.

这是行不通的,因为returninonerroronload函数,并且因为请求是异步的,所以函数不会等到 reuest 完成。

you can achieve this using callback.

您可以使用回调来实现这一点。

function callback(src, value){
                var brick = "<div class='brick small'><a class='delete' href='#'>&times;</a><img src='" + src + "' /><h2><span>" + value + "</span></h2></div>";
                $( ".gridly" ).append( brick );
}

function getThumbnail(name, c)
{
    var image_url = "images/" + name + ".jpg";

    var image = new Image();

    image.onload = function()
    {
        c(image_url, name);
    }
    image.onerror = function()
    {
        c("images/default.jpg", name);
    }

    image.src = image_url;
}

$.each( cycle, function( key, value )
{
    var mapIndex = key;
    var mapValue = value;

    getThumbnail(value, callback);
});