JQ the correct way to get the dynamically loaded picture size share _jquery

Source: Internet
Author: User
Tags browser cache

There are some very error-prone ways to get the size of dynamically loaded pictures, the main reason for this error is:
You call it before the code is downloaded from the Web page, which is not easy to spot when you develop the computer.
The JQuery load () event handles a bug that gets the wrong size when the image is obtained from the browser cache.
The wrong code is:
(error) calling code to get dimensions immediately after HTML has been added

Copy Code code as follows:

var html = ';
$ (' #my_div '). HTML (HTML);
var width = $ (' #my_div img '). width (); May return 0

(error) handling with a jquery load () event

Copy Code code as follows:

var html = ';
var img = $ (HTML);
Html.load (function () {
Return 0 if image are loaded from browser cache
var width = img.width ();
});
$ (' #my_div '). HTML (IMG);

Here's the really right way to use the JavaScript image class:
The right way

Copy Code code as follows:

var html = ';
$ (' #my_div '). HTML (HTML);
var ni = new Image ();
Ni.onload = function () {
var width = ni.width;
}
NI.SRC = Img.attr (URL);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.