Sometimes you need to get the size of the image, which needs to be loaded after the image is loaded. Below, the editor has compiled a summary of several methods for judging whether a JS image is loaded. Let’s take a look.
1. Load event
<script type="text/javascript">$('img').onload = function() {//code}</script>Advantages: Simple and easy to use, without affecting HTML code.
Disadvantages: Only one element can be specified, and the javascipt code must be placed below the image element
2. jquery method
<script type="text/javascript">$(function(){$('.pic1').each(function() {$(this).load(function(){$(this).fadeIn();});});})</script>Note that do not bind the load event in $(document).ready().
Advantages: Element events can be bound in batches and does not affect HTML code content
Disadvantages: The support of the jquery library is required, and the code needs to be placed below the element that needs to be operated.
3. Readystatechange event
<!DOCTYPE HTML><html> <head> <meta charset="utf-"><title>img - readystatechange event</title></head> <body><img id="img" src="http://pic.win.com/wallpaper/f/cbbaea.jpg"><p id="p">loading...</p><script type="text/javascript">img.onreadystatechange = function() {if(img.readyState=="complete"||img.readyState=="loaded"){ p.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.
4. 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('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.
The above content is a summary of the JS method to determine whether the image is loaded by the editor. I hope it will be helpful to everyone. At the same time, I would like to thank you very much for your support for the Wulin Network website!