jQuery: check whether image is loaded

Wait for the image!

This is common task. You’d like to load an image and then show it. With jQuery that is simple enough. Let’s assume this code:

<img src="image.jpg" />
<div>displayed after the image is loaded</div>

This is OK if the div is hidden with jQuery you can show it with adding this code in your javascript:

<script>
    $('img').load(function() {
        $('div').show();
    });
</script>

31 thoughts on “jQuery: check whether image is loaded

  1. Extending this technique you can make a “loading” image appear while the image is loading, and then switch in the image after it has loaded:

    var $image = $(”).css({ display: ‘none’ }).attr({
    src: ‘path/to/image.png’,
    alt: ‘description of image’
    });
    var $loader = $(”).attr({
    src: ‘path/to/loader.gif’
    });
    $(this).append($loader).append($image.load(function() {
    $loader.remove();
    $image.css({ display: ‘inline-block’ });
    }));

    Or you could use ‘inline’ or ‘block’ for the final display property of the image, whatever matches your requirements.

  2. @Weee: you are almost right. I had an issue with IE that when loading multiple images on the same time not all of them call the load event. Strange but I could not reproduce it with single image.

    Howsoever the method is very useful and after some testing you can see is it working in your case or not.

  3. this — is $(image) in this case (cuted from my code):

    if (this.complete || this.readyState === 4) {
        // do on load complete	
    } else {
        $(this).bind('load', function(){	
            // do on load complete	
        });
    }

    Works in safari, firefox, opera. No bugs with cached images.

  4. This solution to Safari document ready bug:

    $(document).ready(function() {
        if (jQuery.browser.safari &amp;&amp; document.readyState != "complete") {
             setTimeout(arguments.callee, 100);
             return;
         }
     
        //code on page ready
    });
  5. Nice article, but the title is pretty misleading. You confuse “check whether” with “wait until”.

    Which is not just nit-picking, as in most cases you would need _both_ things.

  6. Excellent stuff. Thanks for this article. I was wrongly trying $(‘img’).bind(‘load’, function(){}); instead then wondering why it wouldn’t work!

  7. Pretty obvious snippet but it was alluding my brain as a solution for a bug I encountered in my webapp. You saved my life 🙂

  8. If you repeat the function remember to UNBIND!

    $(“button”).click(function(){
    $(‘img’).unbind(“load”).load(function() {
    $(‘div’).show();
    });
    }

    If you don’t unbind when using a repeatable function you’ll have the load even trigger multiple times (as many as you’ve clicked).

  9. What about a dynamically generated img element or dynamicaaly changed src attribute of an img element?

Leave a Reply

Your email address will not be published. Required fields are marked *