There are many articles on the Internet to determine whether the picture has been loaded, but some browsers are not suitable, the following small section to share some of the JavaScript to determine whether the picture has been loaded complete method summary, the specific content as follows:
One. OnLoad Event
By listening to the OnLoad event of the image, it is possible to determine whether the picture has been loaded, compatible with all browsers (the recommended method), and the code example below
?
1234567891011121314151617 |
<!DOCTYPE html>
"en"
>
<meta charset=
"UTF-8"
>
<title>Document</title>
<body>
"img1" src=
"http://pic1.win4000.com/wallpaper/f/51c3bb99a21ea.jpg" alt=
""
>
<script>
// 方法一:图片已经下载完
document.getElementById(
‘img1‘
).onload =
function
(e){
e.stopPropagation();
alert(1);
}
</script>
</body>
|
Two. Determine the complete property of the IMG object (DOM)
When the IMG load completes, the complete object property becomes true, and the code example is as follows:
?
1234567891011121314151617181920 |
<!DOCTYPE html>
"en"
>
<meta charset=
"UTF-8"
>
<title>Document</title>
<body>
"img1" src=
"http://pic1.win4000.com/wallpaper/f/51c3bb99a21ea.jpg" alt=
""
>
<script>
// 方法二:img的complate属性
var timer = setInterval(
function
(){
if (document.getElementById(
‘img1‘
).complete){
clearInterval(timer);
alert(1);
console.log(document.getElementById(
‘img1‘
).complete)
}
}, 10);
</script>
</body>
|
This method is also compatible with all browsers
Three. onReadyStateChange Events
Under IE, the IMG object has the same onreadystatechange event as the Xhr object, which can be Guo Jianting to determine if the picture is loaded and the code example is as follows:
?
1234567891011121314151617 |
<!DOCTYPE html>
"en"
>
<meta charset=
"UTF-8"
>
<title>Document</title>
<body>
"img1" src=
"http://pic1.win4000.com/wallpaper/f/51c3bb99a21ea.jpg" alt=
""
>
<script>
document.getElementById(
‘img1‘
).onreadystatechange =
function
() {
if
(document.getElementById(
‘img1‘
).readyState==
"complete"
||document.getElementById(
‘img1‘
).readyState==
"loaded"
){
alert(1);
}
}
</script>
</body>
|
This method is only available under IE
A summary of how JavaScript determines whether a picture has been loaded