Home >Web Front-end >JS Tutorial >Summary of JavaScript methods to determine whether an image has been loaded_javascript skills

Summary of JavaScript methods to determine whether an image has been loaded_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:16:035827browse

There are many articles on the Internet about determining whether an image has been loaded, but some browsers are not suitable. The following editor will share with you some summary of JavaScript methods for determining whether an image has been loaded. The specific content is as follows:

1.onload event

By listening to the onload event of the image, you can determine whether the image has been loaded. It is compatible with all browsers (w3c recommended method). The code example is as follows

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<img id="img1" src="http://pic1.win4000.com/wallpaper/f/51c3bb99a21ea.jpg" alt="">
<script>
// 方法一:图片已经下载完
document.getElementById('img1').onload = function(e){
e.stopPropagation();
alert(1);
}
</script>
</body>
</html> 

2. Determine the complete attribute of the img object (DOM)

When the img is loaded, the complete object attribute will become true. The code example is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<img id="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>
</html> 

Personally tested this method and it is also compatible with all browsers

Three.onreadystatechange event

Under IE, the img object has the onreadystatechange event like the xhr object. You can use this event to determine whether the image is loaded. The code example is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<img id="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>
</html> 

This method is only available under IE

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn