Sometimes you need to get the size of the image, which only needs to be loaded after the image is loaded. Find the method?
1. Load event
The code copy is as follows:
<!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>
Test, all browsers show "loaded", indicating that all browsers support img load event.
2. Readystatechange event
The code copy is as follows:
<!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, which means that the image has been loaded. Testing that IE6-IE10 supports this event, but other browsers do not.
III. Img's complete attribute
The code copy is as follows:
<!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('Loaded')
})
</script>
</body>
</html>
Polling continuously monitors the complete attribute of img. If true, it means that the image has been loaded and polling is stopped. This property is supported by all browsers.