Sometimes in front-end development work, in order to obtain image information, we need to correctly obtain the size of the image after the image is loaded, and execute the corresponding callback function to produce a certain display effect for the image. This article mainly sorts out several common JavaScript methods for judging when an image is loaded, and explains it through a combination of code and practical applications.
onload method
Execute subsequent javascipt code 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. Onload is used to determine that the image is displayed after the loading is complete.
Advantages: The javascript code part can be placed in any part of the page to load, and can be used on most any images. It is relatively simple to use and easy to understand.
Disadvantages: The onlaod attribute must be affixed to each tag, which is not applicable in some situations where HTML code cannot be directly manipulated or code simplification is required
javascipt native method
Select the image with the specified ID and specify the callback method through onload. After the image is loaded, a prompt with the words "Image loading completed" will pop up.
Disadvantages: Only one element can be specified, and the javascipt code must be placed below the image element
jquery method
Bind an event to each picture element with class pic1, and use jquery's load method to gradually reveal the element.
Note, do not bind the load event in $(document).ready().
Disadvantages: It requires the support of jquery library, and the code needs to be placed below the elements that need to be operated.