Sometimes in front-end development work, in order to obtain image information, we need to correctly obtain the size and size of the image after the image is loaded, and execute the corresponding callback function to make the image produce a certain display effect. This article mainly organizes several common methods for judging the completion of image loading, and explains and explains it through the combination of code and practical applications.
onload method
Execute subsequent javascipt code by adding onload attribute to the img tag and filling in the corresponding function. In the following code example, the img element is not displayed by default. It is determined by onload that the image is displayed after the load is completed.
The code copy is as follows:
<img onload="get(this)" src="..." style='display:none' />
<script type="text/javascript">
function get(ts){
ts.style.display = 'block'; //Show pictures
}
</script>
Advantages: The javascript code section can be placed on any part of the page to load, and can be used on most arbitrary images. It is relatively simple to use and easy to understand.
Disadvantages: Onlaod attribute must be posted on each tag, which is not applicable in some cases where HTML code cannot be directly manipulated or if the code is required to be simplified.
Javascipt native method
Select the picture with the specified ID, specify the callback method through onload, and a prompt with the word "Image Loading Completed" pops up after the picture is loaded.
The code copy is as follows:
<img id="pic1" src="..." />
<script language="JavaScript">
document.getElementById("pic1").onload = function () {
alert("Image loading completed");
}
</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
jquery method
For each image element binding event with class pic1, the element gradually appears through the load method of jquery.
Note that do not bind the load event in $(document).ready().
The code copy is as follows:
<script type="text/javascript">
$(function(){
$('.pic1').each(function() {
$(this).load(function(){
$(this).fadeIn();
});
});
})
</script>
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.