Chrome is wrongly reporting width and height values for images during, or just after, load time. Jquery is used in this code example:
<img id='image01' alt='picture that is 145x134' src='/images/picture.jpg' />
<script>
var img = $( 'img#image01' )
img.width() // would return 145 in Firefox and 0 in Chrome.
img.height() // would return 134 in Firefox and 0 in Chrome.
</script>
If you put the script in a $(function(){}) function, the result is the same. but if you run the code a few seconds after the page has loaded, chrome returns the correct result.
<script>
function example () {
var img = $( 'img#image01' );
img.width() // returns 145 in both Firefox and Chrome.
img.height() // returns 134 in both Firefox and Chrome.
}
window.setTimeout( example, 1000 )
</script>
Also if you specify the width and height values in the img tag, the script seems to work as expected in both Firefox and Chrome.
<img id='image01' src='/images/picture.jpg' width=145 height=134 />
But as you cannot always control the html input, this is not an ideal workaround. Can jQuery be patched with a better workaround for this problem? or will I need to specify the width and height for every image in my code?
Your quoted code doing it inline is getting a reasonable result, as the image may well not be loaded before your code executes. You said that you put it in an
onloadhandler and that also has the same result. Did you really mean anonloadhandler? Because I cannot replicate that result. Note that the jQueryreadyfunction is not anonloadhandler, it happens much earlier than that. To ensure images are loaded, use the image’sloadevent or thewindowloadevent. jQueryreadyhappens a lot earlier than that.So this should work:
…(where
logis something that outputs to the page), and this should work:…but this will not:
…because it happens too soon.
Edit: I really, really should have said in the above: If you’re looking the image’s
loadevent (rather than thewindowload event), you need to check to make sure the image hasn’t already been loaded, because itsloadevent may have already fired. That would look something like this:That will call
loadHandlerat the earliest opportunity, whether the image load won the race or thereadycode won the race.