Three implementations that use JavaScript to determine whether an image is loaded or not

  • 2020-03-30 02:49:15
  • OfStack

Sometimes it is necessary to get the size of the image, which can only be done after the image has been loaded. There are three ways to achieve this, which are described below.

Load event
 
<!DOCTYPE HTML> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>img - load event</title> 
</head> 
<body> 
<img id="img1" src="http://pic1.win4000.com/wallpaper/f/51c3bb99a21ea.jpg"> 
<p id="p1">loading...</p> 
<script type="text/javascript"> 
img1.onload = function() { 
p1.innerHTML = 'loaded' 
} 
</script> 
</body> 
</html> 

In the test, all browsers display "loaded," indicating that all browsers support img load events.

Readystatechange event
 
<!DOCTYPE HTML> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>img - readystatechange event</title> 
</head> 
<body> 
<img id="img1" src="http://pic1.win4000.com/wallpaper/f/51c3bb99a21ea.jpg"> 
<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 is complete and loaded to indicate that the image has been loaded. Test ie6-ie10 to support this event, other browsers do not.

The complete attribute of img
 
<!DOCTYPE HTML> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>img - complete attribute</title> 
</head> 
<body> 
<img id="img1" src="http://pic1.win4000.com/wallpaper/f/51c3bb99a21ea.jpg"> 
<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(' To load ') 
}) 
</script> 
</body> 
</html> 

Polling continuously monitors the complete property of img. If true, the image has been loaded. Stop polling. This property is supported by all browsers.
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/201405040924431.gif? 20144492549 ">  

Related articles: