使用 jQuery 异步加载图像

发布于 2024-10-04 17:28:29 字数 386 浏览 5 评论 0原文

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

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

   },
   error: function(r,x) {

   }
});

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

我尝试使用 .load 方法并且它有效,但我不知道如果图像不可用(404),我如何设置超时。我该怎么做?

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

$.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 .load method 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

帝王念 2024-10-11 17:28:29

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

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

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:

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);
        }
    });
陌路黄昏 2024-10-11 17:28:29

如果您确实需要使用 AJAX...

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

解决方案 1

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

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

因此您可以使用 Ajax 加载图像 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);
});

解决方案2:

欺骗浏览器使用其缓存。当资源位于浏览器缓存中时,这为您提供了一个不错的 fadeIn() 功能:

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

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

干杯,
将要

IF YOU REALLY NEED TO USE 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:

Solution 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:

<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.html for image encoding.

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

Solution2:

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

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

仙气飘飘 2024-10-11 17:28:29

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

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

一段简单的 jQuery 将 data-src 复制到 src,这将在您需要时开始加载图像。就我而言,当页面加载完成时。

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

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

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

<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.

$(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.

ゃ懵逼小萝莉 2024-10-11 17:28:29
$(<img />).attr('src','http://somedomain.com/image.jpg');

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

$(<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.

听,心雨的声音 2024-10-11 17:28:29

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

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

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

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.

装迷糊 2024-10-11 17:28:29

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

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

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

$("img").attr('src','http://somedomain.com/image.jpg');
七分※倦醒 2024-10-11 17:28:29

这也行..

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

This works too ..

var image = new Image();
image.src = 'image url';
image.onload = function(e){
  // functionalities on load
}
$("#img-container").append(image);
圈圈圆圆圈圈 2024-10-11 17:28:29

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>

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)

<script>
 $(document).ready(function() {
 $.ajaxSetup({
    cache: false
});
 $("#placeholder").load("PATH TO IMAGE");
   var refreshId = setInterval(function() {
      $("#placeholder").load("PATH TO IMAGE");
   }, 500);
});
</script>
神爱温柔 2024-10-11 17:28:29

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

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

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

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

$("#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.

双马尾 2024-10-11 17:28:29
//Puedes optar por esta solución:

var img = document.createElement('img');
img.setAttribute('src', element.source)
img.addEventListener('load', function(){
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                            alert('broken image!');
                        } else {
                        $("#imagenesHub").append(img);
                        }
                    });

//Puedes optar por esta solución:

var img = document.createElement('img');
img.setAttribute('src', element.source)
img.addEventListener('load', function(){
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                            alert('broken image!');
                        } else {
                        $("#imagenesHub").append(img);
                        }
                    });

深海里的那抹蓝 2024-10-11 17:28:29
$(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">');
        }
    });
$(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">');
        }
    });
违心° 2024-10-11 17:28:29

现在是 2023 年,异步加载图像不需要 jQuery 或 JavaScript:

loading="lazy" 属性 会处理它。

<img src="image.jpg" alt="..." loading="lazy" />

当用户滚动到靠近 DOM 中图像的位置时,浏览器将开始加载图像。

你可以看看MDN上这篇关于延迟加载的文章: https: //developer.mozilla.org/en-US/docs/Web/Performance/Lazy_loading

It is 2023 and neither jQuery, nor JavaScript are needed to asynchronously load images:

The loading="lazy" attribute will take care of it.

<img src="image.jpg" alt="..." loading="lazy" />

The browser will start loading the image when the user scrolls close to its position in the DOM.

You can take a look at this article from MDN on lazy loading: https://developer.mozilla.org/en-US/docs/Web/Performance/Lazy_loading

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文