1

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

2
  • 1
    Where is your code that calls .load? Commented Feb 25, 2013 at 18:22
  • Can you just chain a .attr('width') to whatever code you're using to change the src? You need to post your code and clarify your question also, it's very confusing. Commented Feb 25, 2013 at 18:23

2 Answers 2

3

.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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.