开发者

How do I determine when an image has finished loading?

I have a block of php code that loads an image at random. I'm trying to determine wh开发者_JAVA百科en the image has loaded so I can perform some additional actions on it. Here is how I'm currently loading my image:

// Gets my image
$sql = "SELECT id FROM images WHERE user_id=$owner_user_id LIMIT 0,1";
$imgres = mysql_query($sql);
if ($imgres) {
    $imgrow = mysql_fetch_array($imgres, MYSQL_ASSOC);
    if (!empty($imgrow)) {
        echo ('<image src="img.php?id=' . $imgrow['id'] . '" id="profile_img" style="visibility:hidden"/>');
    }
}

One of the actions I need to do is get the width of the image. I'm getting the image like so:

alert("IMAGE WIDTH:"+$('#profile_img').width());

It currently returns 0 because it's being called prior to the image being loaded. I've tried adding this method call to my document.ready block but it still gets called prior to the image being loaded. Is there an easy way to determine when the image has loaded?


$(document).ready(function(){
    $('#img_id').load(function() {
       alert('image is loaded');
        });
});

this will do the trick


you can bind a load event handler to your image with jquery:

http://api.jquery.com/load-event/


$("#profile_img").load(function(){
   alert(("IMAGE WIDTH:"+$('#profile_img').width())
});

http://api.jquery.com/load-event/


This really has nothing to do with PHP; image loading is done client side, so you'll need to do it in the Javascript side of things. You'll be dealing with Javascript events - here's a primer:

http://www.quirksmode.org/js/introevents.html

Luckily, jQuery has a built-in function to bind to the event for you (even called load()!) which allows you to pass a callback to fire once that content is loaded.


Your best bet is to preload the image in JavaScript prior to the DOM loading at all:

<SCRIPT language="JavaScript">
  preload_image = new Image(25,25); 
  preload_image.src="http://mydomain.com/image.gif"; 
</SCRIPT>

Do NOT use jQuery .load() to test when images are loaded. According to the jQuery docs:

•It doesn't work consistently nor [is it] reliably cross-browser

•It doesn't fire correctly in WebKit if the image src is set to the same src as before

•It doesn't correctly bubble up the DOM tree

•Can cease to fire for images that already live in the browser's cache

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜