How does JavaScript determine if an image is loaded to get its size

  • 2020-03-30 02:54:02
  • OfStack

Sometimes you need to get the size of the image, and you can't do that until the image is loaded. How?

Load event
 
<!DOCTYPE HTML> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>img - load event</title> 
</head> 
<body> 
<img id="img1" src="http://pic1.xxx.com/wall/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.xxx.com/wall/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.xxx.com/wall/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.

Related articles: