使用 jQuery 异步加载图像 [英] Asynchronously load images with jQuery

查看:31
本文介绍了使用 jQuery 异步加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 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?

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

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?

推荐答案

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

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

这篇关于使用 jQuery 异步加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆