最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Best practice to get image info - Stack Overflow

programmeradmin1浏览0评论

I tried to load an image into an HTML element using JQuery ad use the image properties to do other things. What i tried to do is something like this:

var img = new Image();
img.src = "icon.png";
var width = img.width;
var height = img.height;
$("#element").css("background-image", "url(" + img.src + ")");
//use width and height...

It works most of the times but i found that sometimes "width" and "height" are set to 0. Doing some searches I found that the image load is an asynchronous job, so it happens that i try to read the properties when it is still not loaded. I found that there is an onLoad event that i can use to specify a callback function when the image is loaded.

I wonder if it is the best way to do such things. Let be the case, for example, that I only need some information about an image but i don't need to display it, and i want to manage that information client side. Do i need to load the image? Is there some other way to obtain such information?

I tried to load an image into an HTML element using JQuery ad use the image properties to do other things. What i tried to do is something like this:

var img = new Image();
img.src = "icon.png";
var width = img.width;
var height = img.height;
$("#element").css("background-image", "url(" + img.src + ")");
//use width and height...

It works most of the times but i found that sometimes "width" and "height" are set to 0. Doing some searches I found that the image load is an asynchronous job, so it happens that i try to read the properties when it is still not loaded. I found that there is an onLoad event that i can use to specify a callback function when the image is loaded.

I wonder if it is the best way to do such things. Let be the case, for example, that I only need some information about an image but i don't need to display it, and i want to manage that information client side. Do i need to load the image? Is there some other way to obtain such information?

Share Improve this question asked Nov 23, 2012 at 14:12 giocarminegiocarmine 5801 gold badge14 silver badges30 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You have to wait for the image to be loaded:

var img = new Image();
img.onload = function() {
  var width = img.width;
  var height = img.height;
  $("#element").css("background-image", "url(" + img.src + ")");
};
img.src = "icon.png";

Because the image has to be fetched from the URL assigned to the "src" attribute, the operation is treated asynchronously. That is, you're not guaranteed that the image will be available for the statement following the assignment of the "src" attribute.

It works sometimes because your image may be cached.

发布评论

评论列表(0)

  1. 暂无评论