Sometimes we in the front-end development work in order to obtain the information of the picture, we need to be loaded after the picture is completed before the image can be correctly obtained size, and the corresponding callback function to make the picture to produce some kind of display effect. This paper mainly deals with several common methods of javascipt judgment picture loading, and explains it by combining code with practical application.
OnLoad method
Execute subsequent javascipt code by adding the OnLoad property to the IMG tag and filling in the appropriate function. The following code example shows that the IMG element is not displayed by default, and the image is displayed after the load is completed by onload.
1234567 |
<img class="Pic1" onload="Get (This)" src="..." style=' display:none ' /> <script Type="Text/javascript"> function get(ts){ ts. Style. Display = ' block '; //Show pictures }</script> |
Pros: You can load the JavaScript code part on any part of the page and can be used on most arbitrary images. The use is relatively simple and easy to understand.
Cons: The onlaod attribute must be affixed on each label, not applicable in some cases where the HTML code cannot be manipulated directly or requires code refinement
Javascipt Native method
Select the picture with the specified ID, specify the callback method via OnLoad, and the "picture loading completed" prompt pops up after the picture is loaded.
1234567 |
<img id="Pic1" src="..." /> <script Language="JavaScript"> document. getElementById("Pic1"). OnLoad = function () { alert("Picture loading Completed"); }</script> |
Pros: Easy to use, without affecting HTML code.
Disadvantage: Only one element can be specified, Javascipt code must be placed below the picture element
jquery method
Bind events for each picture element of class Pic1, and use the jquery load method to get the elements out of the way.
Note that you do not bind the Load event in the. Ready ().
123456789 |
<script Type="Text/javascript"> $(function(){ $('. Pic1 '). Each(function() { $(this). Load(function(){ $(this). FadeIn(); }); });})</script> |
Pros: You can bulk bind element events without affecting HTML code content
Cons: Requires the support of the jquery library, and the code needs to be placed below the element that needs to be manipulated.
JavaScript Determines whether a picture is loaded and finished