JavaScript判断图片是否加载完成的三种方式 (转)

一、load事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>img - load event</title>
</head>
<body>
    <p id="p1">loading...</p>
    <script type="text/javascript">
        img1.onload = function() {
            p1.innerHTML = 'loaded'
        }
    </script>
</body>
</html>

测试,所有浏览器都显示出了“loaded”,说明所有浏览器都支持img的load事件。

二、readystatechange事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>img - readystatechange event</title>
</head>
<body>
    <p id="p1">loading...</p>
    <script type="text/javascript">
        img1.onreadystatechange = function() {
            if(img1.readyState=="complete"||img1.readyState=="loaded"){
                p1.innerHTML = 'readystatechange:loaded'
            }
        }
    </script>
</body>
</html>

readyState为complete和loaded则表明图片已经加载完毕。测试IE6-IE10支持该事件,其它浏览器不支持。

三、img的complete属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>img - complete attribute</title>
</head>
<body>
    <p id="p1">loading...</p>
    <script type="text/javascript">
        function imgLoad(img, callback) {
            var timer = setInterval(function() {
                if (img.complete) {
                    callback(img)
                    clearInterval(timer)
                }
            }, 50)
        }
        imgLoad(img1, function() {
            p1.innerHTML('加载完毕')
        })
    </script>
</body>
</html>

轮询不断监测img的complete属性,如果为true则表明图片已经加载完毕,停止轮询。该属性所有浏览器都支持。

JavaScript判断图片是否加载完成的三种方式 (转)

<!DOCTYPE HTML>

<html>
<head>
    <meta charset="utf-8">
    <title>img - complete attribute</title>
</head>
<body>
    <p id="p1">loading...</p>
    <script type="text/javascript">
        function imgLoad(img, callback) {
            var timer = setInterval(function() {
                if (img.complete) {
                    callback(img)
                    clearInterval(timer)
                }
            }, 50)
        }
        imgLoad(img1, function() {
            p1.innerHTML('加载完毕')
        })
    </script>
</body>
</html>
上一篇:使用Winform程序作为WCF服务的宿主


下一篇:JavaScript判断图片是否加载完成