JavaScript method summary to determine if an image has been loaded

  • 2020-12-16 05:51:30
  • OfStack

There are many articles on the Internet about whether the image has been loaded or not, but some browsers are not suitable for it. Here is a summary of JavaScript's methods for determining whether the image has been loaded or not. The specific content is as follows:

1. onload events

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 shown below


<!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>
//  methods 1 : The pictures have been downloaded 
document.getElementById('img1').onload = function(e){
e.stopPropagation();
alert(1);
}
</script>
</body>
</html> 

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

When img is loaded, the complete object property changes to true, with the following code example:


<!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>
//  methods 2 : img the complate attribute 
var timer = setInterval(function(){
if (document.getElementById('img1').complete){
clearInterval(timer);
alert(1);
console.log(document.getElementById('img1').complete)
}
}, 10);
</script>
</body>
</html> 

This method is also compatible with all browsers

3. onreadystatechange events

Under ie, img object and xhr object 1 have AN onreadystatechange event, which can be used to determine whether the image has been loaded through Guo Jianting. 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


Related articles: