检测特定图像何时加载完成

3

我在一个网页上有一张图片,这张图片是由服务器端的CGI程序动态生成的。定期地,这张图片会被计时器刷新和/或根据用户输入进行更改。因此,我有一个JavaScript函数,如下所示:

// <img id="screen" src=""> is elsewhere in the page
function reloadImage() {
    $("#screen").attr("src", make_cgi_url_based_on_form_inputs());
}

这个功能很好用,但有时需要加载一段时间才能显示图像。所以我想要一个类似于“正在加载图像”的消息出现,但是当图像加载完成并在浏览器中显示时,该消息应该消失。

有没有一种JavaScript事件可以实现这个功能?或者,是否有其他方法可以通过Ajax或其他方式加载/更改/更新图像,并检测加载何时完成?


可能是JavaScript回调以知道何时加载图像的重复问题 - Ciro Santilli OurBigBook.com
1个回答

9
你可以尝试这个jQuery解决方案:http://jqueryfordesigners.com/image-loading/
$(function () {
        var img = new Image();
        $(img).load(function () {
            //$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
            $(this).hide();
            $('#loader').removeClass('loading').append(this);
            $(this).fadeIn();
        }).error(function () {
            // notify the user that the image could not be loaded
        }).attr('src', 'http://farm3.static.flickr.com/2405/2238919394_4c9b5aa921_o.jpg');
    });

谢谢!我完全错过了jQuery加载文档中提到的load函数可以用于图像以及窗口和框架的部分。 - Eli Courtwright

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接