开发者

How does the browser know if an image is loaded?

I need to have a function called after a larger image is loaded on the page. I've tried some various solutions that I've found on here and around the web, but none either fit or work. Here's what I've tried that seems to make the most sense...and this is using jQuery

var imgs = $('#bgStage img.bg'),
           imgCnt = imgs.length,
           cnt = 0;

imgs.load(function () {
    cnt++;
    if (imgCnt === cnt) {
        homeSlider();
    }
}).each(function () {
    if (this.complete) {
        $(this).trigger('load');
    }
});

This doesn't seem to wait until the img.bg is loaded. The homeSlider() function is called and started as I still see the image stil开发者_运维问答l loading.

So, I am wondering how a browser determines an image is loaded? Is it when it can read the width and height? Because I am defining the width and height in the CSS for the image to force it to be a certain size.

If anyone has any insight as to what makes the onload event fire for an image, that'd be great! Thanks.


You can always check for $('img').length();


Here's a sample code that should work. I did a project that needed this and I remember that some problems might include:

  • The browser caches the image (IE i believe) so I had to append ?[random] at the end
  • Maybe you have to set the src javascriptly so that your event is hooked at the right time

Sample code:

<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){       
    $('#imageSample')
        .load(function(){
            alert($('#imageSample').width());
            alert($('#imageSample').height());
        })
       .attr('src', 'http://www.gimp.org/tutorials/Lite_Quickies/quintet_hst_big.jpg?' + new Date());

});
</script>
<style type="text/css"></style>
</head>
<body>
    <img id="imageSample" src="" alt="" />
</body>
</html>


Images might be cached, try this: http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js


Use something simple like so:

var loaded =  false;
var len = $('#bgStage img.bg'), c = 0;
$('#bgStage img.bg').each(function(){

    $(this).attr('src',$(this).attr('src') + new Date()); //Remove caching.

    $(this).bind('onload',function(){

        //Other Stuff here!

        if(c == len)
        {
            HomeSlider();
        }
        c++; //Increment
    });
});

Tell me how it goes :)


Each image has a complete property. Unfortunately not all browsers support it. They always report true, even if the image hasn't loaded at all. IE gets it right. ;-)

http://simon.html5.org/test/html/semantics/img/src/ (not mine)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜