Home  >  Article  >  Web Front-end  >  3 ways to use JavaScript to determine whether an image has been loaded_javascript skills

3 ways to use JavaScript to determine whether an image has been loaded_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:09:511173browse

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.

Copy code The code is as follows:




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.

Copy code The code is as follows:





Advantages: Simple and 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 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().

Copy code The code is as follows:



Advantages: Element events can be bound in batches without affecting the HTML code content

Disadvantages: It requires the support of jquery library, and the code needs to be placed below the elements that need to be operated.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn