Reputation: 2991
I have an img element and each time I change its src dynamically I want to get new image's width (after it's completely loaded)
.load() seems not trigger if image is in cache already(?), but I don't want to load it again in this case, as:
'image.jpg?' + new Date().getTime();
would(?)
What is the best way to do it?
Edit:
$('#test img:first').load(function() {
console.log($(this).width());
});
seems it doesn't trigger if images in cache already
Upvotes: 1
Views: 1423
Reputation: 707178
.load()
will not trigger if the image is in the cache and the onload
handler is not installed on before the .src
property is set on the image in some browsers (IE).
If the image is being dynamically created with javascript, then just make sure that the onload
handler is assigned BEFORE the .src
property is set.
If the image is in the page HTML, then the only way to guarantee you get an onload event for that particular image is if you have an onload handler specified in the HTML itself. There is no way to install an onload handler with javascript for an image in your HTML and make sure that it gets called because the image may already be loaded before any javascript runs.
You can check to see if an image is already loaded with the .complete
property.
So, a work-around for an image in your HTML would be this:
var img = $('#test img:first');
if (!img[0].complete) {
img.load(function() {
// onload code here
});
} else {
// image already loaded
}
Upvotes: 3
Reputation: 191729
In modern browsers, you can use the complete
property to check that an image has completed loading even if it's cached. Something like:
$("#myimg").on('load', function () { /* get new width */ });
if ($("#myimg").attr('src', 'image.jpg').prop('complete')) {
/* get new width */
}
(just in case .prop
does not work, you can use .get(0).complete
).
Upvotes: 1