JavaScript implements three methods to determine whether the image is loaded or not

  • 2020-05-16 06:15:01
  • OfStack

Sometimes in the front-end development work, in order to get the information of the image, we need to get the size of the image correctly after the image is loaded, and execute the corresponding callback function to make the image produce a certain display effect. This paper mainly sorted out several common methods of javascipt to judge the completion of picture loading, and explained and explained through the combination of code and practical application.

onload method

The subsequent javascipt code is executed by adding the 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. The image will be displayed after the loading is judged by onload.


<img class="pic1" onload="get(this)" src="..." style='display:none' />
 
<script type="text/javascript">
function get(ts){
 ts.style.display = 'block';  // Display images
}
</script>

Advantages: you can place parts of the javascript code on any part of the page and use it on most arbitrary images. Easy to use, easy to understand.

Cons: you must have the onlaod attribute on every tag, which is not applicable in cases where you cannot directly manipulate the HTML code, or where you need to streamline the code

javascipt native method

Select the image specified by ID, specify the callback method through onload, and the "image loading is completed" prompt will pop up after the image loading is completed.


<img id="pic1" src="..." />
 
<script language="JavaScript">
    document.getElementById("pic1").onload = function () {
        alert(" Image loading is complete ");
    }
</script>

Pros: easy to use, does not affect HTML code.

Disadvantages: only one element can be specified, and the javascipt code must be placed below the image element

jquery method

Bind events for each image element for which class is pic1, and the element is gradually rendered through jquery's load method.

Note that you do not bind load events in $(document).ready().


<script type="text/javascript">
$(function(){
 $('.pic1').each(function() {
  $(this).load(function(){
   $(this).fadeIn();
  });
    });
})
</script>

Advantages: you can batch bind element events without affecting the HTML code content

Cons: jquery library support is required, and code needs to be placed below the elements that need to be manipulated.


Related articles: