When a div is hidden (display:none
) the browser will not load the images that are inside it. Is there a way to tell the browser to load the image?
I've added some preloading, wrapped it into a function and that does the trick:
function getImageDimension(el, onReady) {
var src = typeof el.attr === 'function' ? el.attr('src') : el.src !== undefined ? el.src : el;
var image = new Image();
image.onload = function(){
if(typeof(onReady) == 'function') {
onReady({
width: image.width,
height: image.height
});
}
};
image.src = src;
}
Can be used as:
getImageDimension($('#img1'), function(d){ alert(d.height); });
var url = 'http://urology.jhu.edu/patrickwalsh/photo1.jpg';
getImageDimension(url, function(d){ alert(d.height); });
Check out this thread.
Don't load hidden images
You could try pre-loading the images using jquery - check out this SO answer:
Preloading images with jQuery
This should pre-load them before you even decide to display them.
I believe this is only true for items whose parent is "display:none"
See this article on the matter http://dev.jquery.com/ticket/125
Also, see this example (save as an .html file)
<html>
<head>
<title>Example</title>
<script type="text/javascript">
$(document).ready(function(){
alert($("#target").height());
});
</script>
</head>
<body>
<div id="parent" style="display:none;">
<div id="target" style="height:100px;display:block;">
a
</div>
</div>
</body>
</html>
Make the div visible, but position it outside the page with position: absolute;
.
If your "other code" doesn't let you do this either, create a new image node with the same URL, position it outside the page, wait until it's loaded, read its height and destroy.