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 badges1 Answer
Reset to default 7You 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.