Javascript 使用 jQuery 异步加载图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4285042/
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-08-23 11:43:50  来源:igfitidea点击:

Asynchronously load images with jQuery

javascriptjqueryajaximagejquery-load

提问by Arief

I want to load external images on my page asynchronously using jQueryand I have tried the following:

我想使用 jQuery 在我的页面上异步加载外部图像,我尝试了以下操作:

$.ajax({ 
   url: "http://somedomain.com/image.jpg", 
   timeout:5000,
   success: function() {

   },
   error: function(r,x) {

   }
});

But it always returns error, is it even possible to load image like this?

但它总是返回错误,甚至可以像这样加载图像吗?

I tried to use .loadmethod and it works but I have no idea how I can set timeout if the image is not available (404). How can I do this?

我尝试使用.load方法并且它有效,但是如果图像不可用(404),我不知道如何设置超时。我怎样才能做到这一点?

回答by karim79

No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:

不需要ajax。您可以创建一个新的图像元素,设置其源属性,并在完成加载后将其放置在文档中的某个位置:

var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
    .on('load', function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            alert('broken image!');
        } else {
            $("#something").append(img);
        }
    });

回答by mschmoock

IF YOU REALLY NEED TO USE AJAX...

如果你真的需要使用 AJAX ......

I came accross usecases where the onload handlers were not the right choice. In my case when printing via javascript. So there are actually two options to use AJAX style for this:

我遇到过 onload 处理程序不是正确选择的用例。就我而言,当通过 javascript 打印时。因此,实际上有两种选择可以为此使用 AJAX 样式:

Solution 1

解决方案1

Use Base64 image data and a REST image service. If you have your own webservice, you can add a JSP/PHP REST script that offers images in Base64 encoding. Now how is that useful? I came across a cool new syntax for image encoding:

使用 Base64 图像数据和 REST 图像服务。如果您有自己的网络服务,您可以添加一个 JSP/PHP REST 脚本,以提供 Base64 编码的图像。现在这有什么用?我遇到了一种很酷的图像编码新语法:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhE..."/>

So you can load the Image Base64 data using Ajax and then on completion you build the Base64 data string to the image! Great fun :). I recommend to use this site http://www.freeformatter.com/base64-encoder.htmlfor image encoding.

因此,您可以使用 Ajax 加载 Image Base64 数据,然后在完成后将 Base64 数据字符串构建到图像中!非常有趣 :)。我建议使用此站点http://www.freeformatter.com/base64-encoder.html进行图像编码。

$.ajax({ 
    url : 'BASE64_IMAGE_REST_URL', 
    processData : false,
}).always(function(b64data){
    $("#IMAGE_ID").attr("src", "data:image/png;base64,"+b64data);
});

Solution2:

解决方案2:

Trick the browser to use its cache. This gives you a nice fadeIn() when the resource is in the browsers cache:

欺骗浏览器使用其缓存。当资源在浏览器缓存中时,这会为您提供一个很好的fadeIn():

var url = 'IMAGE_URL';
$.ajax({ 
    url : url, 
    cache: true,
    processData : false,
}).always(function(){
    $("#IMAGE_ID").attr("src", url).fadeIn();
});   

However, both methods have its drawbacks: The first one only works on modern browsers. The second one has performance glitches and relies on assumption how the cache will be used.

但是,这两种方法都有其缺点:第一种方法仅适用于现代浏览器。第二个有性能故障并且依赖于将如何使用缓存的假设。

cheers, will

欢呼,将

回答by htho

Using jQuery you may simply change the "src" attribute to "data-src". The image won't be loaded. But the location is stored withthe tag. Which I like.

使用 jQuery,您可以简单地将“src”属性更改为“data-src”。图像不会被加载。但是位置标签一起存储。我喜欢的。

<img class="loadlater" data-src="path/to/image.ext"/>

A Simple piece of jQuery copies data-src to src, which will start loading the image when you need it. In my case when the page has finished loading.

一个简单的 jQuery 将 data-src 复制到 src,它将在您需要时开始加载图像。在我的情况下,页面已完成加载。

$(document).ready(function(){
    $(".loadlater").each(function(index, element){
        $(element).attr("src", $(element).attr("data-src"));
    });
});

I bet the jQuery code could be abbreviated, but it is understandable this way.

我敢打赌 jQuery 代码可以缩写,但这样可以理解。

回答by Jaseem

$(<img />).attr('src','http://somedomain.com/image.jpg');

Should be better than ajax because if its a gallery and you are looping through a list of pics, if the image is already in cache, it wont send another request to server. It will request in the case of jQuery/ajax and return a HTTP 304 (Not modified) and then use original image from cache if its already there. The above method reduces an empty request to server after the first loop of images in the gallery.

应该比 ajax 更好,因为如果它是一个画廊并且您正在循环浏览图片列表,如果图像已经在缓存中,它不会向服务器发送另一个请求。它将在 jQuery/ajax 的情况下请求并返回 HTTP 304(未修改),然后使用缓存中的原始图像(如果它已经存在)。上述方法减少了图库中第一次循环图像后对服务器的空请求。

回答by phpcoding

You can use a Deferred objects for ASYNC loading.

您可以使用延迟对象进行异步加载。

function load_img_async(source) {
    return $.Deferred (function (task) {
        var image = new Image();
        image.onload = function () {task.resolve(image);}
        image.onerror = function () {task.reject();}
        image.src=source;
    }).promise();
}

$.when(load_img_async(IMAGE_URL)).done(function (image) {
    $(#id).empty().append(image);
});

Please pay attention: image.onload must be before image.src to prevent problems with cache.

请注意:image.onload 必须在 image.src 之前,以防止出现缓存问题。

回答by slobodan

If you just want to set the source of the image you can use this.

如果您只想设置图像的来源,您可以使用它。

$("img").attr('src','http://somedomain.com/image.jpg');

回答by Basilin Joe

This works too ..

这也有效..

var image = new Image();
image.src = 'image url';
image.onload = function(e){
  // functionalities on load
}
$("#img-container").append(image);

回答by Poelinca Dorin

use .load to load your image. to test if you get an error ( let's say 404 ) you can do the following:

使用 .load 加载您的图像。要测试您是否收到错误(例如 404 ),您可以执行以下操作:

$("#img_id").error(function(){
  //$(this).hide();
  //alert("img not loaded");
  //some action you whant here
});

careful - .error() event will not trigger when the src attribute is empty for an image.

小心 - 当图像的 src 属性为空时, .error() 事件不会触发。

回答by benhowdle89

AFAIK you would have to do a .load() function here as apposed to the .ajax(), but you could use jQuery setTimeout to keep it live (ish)

AFAIK 你必须在这里做一个 .load() 函数作为 .ajax(),但你可以使用 jQuery setTimeout 来保持它的活动 (ish)

<script>
 $(document).ready(function() {
 $.ajaxSetup({
    cache: false
});
 $("#placeholder").load("PATH TO IMAGE");
   var refreshId = setInterval(function() {
      $("#placeholder").load("PATH TO IMAGE");
   }, 500);
});
</script>

回答by MadhaviLatha Bathini

$(function () {

$(函数(){

    if ($('#hdnFromGLMS')[0].value == 'MB9262') {
        $('.clr').append('<img src="~/Images/CDAB_london.jpg">');
    }
    else
    {
        $('.clr').css("display", "none");
        $('#imgIreland').css("display", "block");
        $('.clrIrland').append('<img src="~/Images/Ireland-v1.jpg">');
    }
});