Javascript - 如何在不使用/显示图像的情况下对图像进行异步加载

时间:2015-04-14 11:18:05

标签: javascript jquery asynchronous

当用户上传图片(ajax)时,我想使用gif图像(loding indication - speening wheel)。但是我希望在用户点击"上传"之后立即显示它。按钮,下载gif图像没有延迟。

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

您可以通过不同方式预加载图片,请参阅this link

        var images = new Array()
        function preload() {
            for (i = 0; i < preload.arguments.length; i++) {
                images[i] = new Image()
                images[i].src = preload.arguments[i]
            }
        }
        preload(
            "http://domain.tld/gallery/image-001.jpg",
            "http://domain.tld/gallery/image-002.jpg",
            "http://domain.tld/gallery/image-003.jpg"
        )

是javascript方式,网站还会显示如何在html和css中执行此操作,具体取决于您希望如何执行此操作。

答案 2 :(得分:1)

使用css

<div id="preload">
  <img src="ajax-indicator.gif"/>
</div>

#preload {
    display: none;
}

即使浏览器不可见,浏览器也会加载图片。