672

In jQuery when you do this:

$(function() {
   alert("DOM is loaded, but images not necessarily all loaded");
});

It waits for the DOM to load and executes your code. If all the images are not loaded then it still executes the code. This is obviously what we want if we're initializing any DOM stuff such as showing or hiding elements or attaching events.

Let's say though that I want some animation and I don't want it running until all the images are loaded. Is there an official way in jQuery to do this?

The best way I have is to use <body onload="finished()">, but I don't really want to do that unless I have to.

Note: There is a bug in jQuery 1.3.1 in Internet Explorer which actually does wait for all images to load before executing code inside $function() { }. So if you're using that platform you'll get the behavior I'm looking for instead of the correct behavior described above.

Community
  • 1
  • 1
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
  • 3
    doesn't `$("img").load()` work? – Lucas Dec 21 '12 at 05:57
  • 1
    I think it may worth mentioning that if you set the dimensions attributes, you ca safely execute some code in ready function that rely on those dimensions. With php you can grab them with http://php.net/manual/en/function.getimagesize.php on upload to store them in db or before output to browser. – Alqin Jan 29 '13 at 21:27
  • if you want something doing an incredible job, then check out the extremely good & popular imagesloaded javascript library mentioned in this answer below http://stackoverflow.com/a/26458347/759452 – Adriano Nov 13 '14 at 16:34

11 Answers11

1076

With jQuery, you use $(document).ready() to execute something when the DOM is loaded and $(window).on("load", handler) to execute something when all other things are loaded as well, such as the images.

The difference can be seen in the following complete HTML file, provided you have a lot of jollyrogerNN JPEG files (or other suitable ones):

<html>
    <head>
        <script src="jquery-1.7.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                alert ("done");
            });
        </script>
    </head><body>
        Hello
        <img src="jollyroger00.jpg">
        <img src="jollyroger01.jpg">
        // : 100 copies of this in total
        <img src="jollyroger99.jpg">
    </body>
</html>

With that, the alert box appears before the images are loaded, because the DOM is ready at that point. If you then change:

$(document).ready(function() {

into:

$(window).on("load", function() {

then the alert box doesn't appear until after the images are loaded.

Hence, to wait until the entire page is ready, you could use something like:

$(window).on("load", function() {
    // weave your magic here.
});
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 32
    *smacks forehead* +1 totally forgot that. $(window).load() won't fire until images are done. – Paolo Bergantino Feb 13 '09 at 07:05
  • thanks! that did it. i didn't actually notice how bad the effect was until i tested locally in Safari on Windows. then it became painfully obvious that i needed to do this. smacks forehead – Simon_Weaver Feb 13 '09 at 07:12
  • except you don't need the waiting thing. just put the logic in load(..). is that what you meant by 'smacks forehead'? – Simon_Weaver Feb 13 '09 at 07:13
  • Nah, I just smacked my forehead because of the answer. he initially didn't have the waiting stuff. – Paolo Bergantino Feb 13 '09 at 07:25
  • Just so you know, Safari sometimes fires onload before images have completely loaded. I can't reproduce it reliably but it does happen. – eyelidlessness Feb 13 '09 at 08:33
  • @eyelidlessness - so is that going to also affect $(window).load or just body.onload ? – Simon_Weaver Feb 13 '09 at 09:10
  • 11
    I've done the same. Even, read through an answer not knowing it was me and still not understanding it. – Rimian Sep 17 '10 at 05:57
  • I just want you to know, that this tip rocks. I was having a problem with a picture slider that fades out an image (#current_pic), then changes the src, then fades the same #current_pic back in. The browser kept trying to show the image before it loaded --> and not fading. Then I used: $("#current_pic").load(function{ $("#current_pic").fadeIn('slow'); }); and the browser waits until loading and the slick fadeIn action works. Thanks! –  Aug 18 '10 at 01:31
  • 24
    Just a note - this doesn't seem to work under Chromium (and I presume Chrome). The $(window).ready event seems to fire the same as $(document).ready - prior to images being completed. – Nathan Crause Mar 02 '12 at 22:00
  • 24
    but it's $(window).load(function()) – TJ- Dec 27 '12 at 20:22
  • 2
    $(window).load(), $(window).ready() and $(document).ready() are all firing for me before images load in Chromium. – Jonathan Hall Dec 11 '13 at 20:04
  • $(window).load(), $(window).ready() and $(document).ready() all fail for me in IE11. They fire before images set through css are loaded. – KyorCode Feb 14 '14 at 14:39
  • 1
    try $(window).on("load",function(){ – Matt Ramirez Mar 14 '14 at 14:29
  • 3
    @KyorCode Are you sure it's not just because the images in IE were cached? If that happens, they won't fire a "load" event at all. [This article](http://css-tricks.com/snippets/jquery/fixing-load-in-ie-for-cached-images/) helps to get around this issue. – Jamie Barker May 19 '14 at 15:01
  • @TJ- fixed that –  Jan 11 '17 at 11:11
  • I am using $(window).load on a project and callback is callback but images are not ready yet... So, this is not working. EDIT: The images are using lazy loading – Loenix Jul 18 '22 at 14:00
160

I wrote a plugin that can fire callbacks when images have loaded in elements, or fire once per image loaded.

It is similar to $(window).load(function() { .. }), except it lets you define any selector to check. If you only want to know when all images in #content (for example) have loaded, this is the plugin for you.

It also supports loading of images referenced in the CSS, such as background-image, list-style-image, etc.

waitForImages jQuery plugin

Example Usage

$('selector').waitForImages(function() {
    alert('All images are loaded.');
});

Example on jsFiddle.

More documentation is available on the GitHub page.

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    Thank you!! $.load() wasn't working for me, but this does the trick perfectly. – ashastral Sep 30 '11 at 22:31
  • I use Chrome Version 22.0.1229.94 and this plugin, and I tried to read the offsets from the loaded images within the waitFormImages: ```('img selector').each(function(index) { var offset = $(this).offset(); ...});``` , however, offset.top is still zero. Why? – basZero Nov 01 '12 at 16:14
  • 1
    @basZero Difficult to tell without more context. Please raise an issue on the [Issues](https://github.com/alexanderdickson/waitForImages/issues) page. – alex Nov 01 '12 at 20:47
  • Its not working for me when the images are cahced. Does any1 hav a workaround for this ? – Mandeep Jain Jan 29 '13 at 05:50
  • @MandeepJain Open an [issue](https://github.com/alexanderdickson/waitForImages/issues) with a minimal test case. – alex Apr 02 '13 at 22:59
  • This library helped me a lot and should have been part of jquery. Heck even .load() has a caveat http://api.jquery.com/load/ – cr8ivecodesmith Jun 06 '13 at 11:37
  • Could you update the jsFiddle? (It's not working anymore due to github not being a CDN) – Batist Feb 19 '16 at 08:34
  • 2
    Its basically analog to imagesLoaded but it works with srcsets too. Exactly what i was looking for! Great plugin! – Fabian S. Jul 13 '16 at 11:15
47

$(window).load() will work only the first time the page is loaded. If you are doing dynamic stuff (example: click button, wait for some new images to load), this won't work. To achieve that, you can use my plugin:

Download

/**
 *  Plugin which is applied on a list of img objects and calls
 *  the specified callback function, only when all of them are loaded (or errored).
 *  @version: 1.0.0 (Feb/22/2010)
 */

(function($) {
$.fn.batchImageLoad = function(options) {
    var images = $(this);
    var originalTotalImagesCount = images.size();
    var totalImagesCount = originalTotalImagesCount;
    var elementsLoaded = 0;

    // Init
    $.fn.batchImageLoad.defaults = {
        loadingCompleteCallback: null, 
        imageLoadedCallback: null
    }
    var opts = $.extend({}, $.fn.batchImageLoad.defaults, options);
        
    // Start
    images.each(function() {
        // The image has already been loaded (cached)
        if ($(this)[0].complete) {
            totalImagesCount--;
            if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
        // The image is loading, so attach the listener
        } else {
            $(this).load(function() {
                elementsLoaded++;
                
                if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);

                // An image has been loaded
                if (elementsLoaded >= totalImagesCount)
                    if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
            });
            $(this).error(function() {
                elementsLoaded++;
                
                if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
                    
                // The image has errored
                if (elementsLoaded >= totalImagesCount)
                    if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
            });
        }
    });

    // There are no unloaded images
    if (totalImagesCount <= 0)
        if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
};
})(jQuery);
hyankov
  • 4,049
  • 1
  • 29
  • 46
  • 1
    just in case anybody needs a usage example to the BatchImagesLoad plugin: http://www.yankov.us/batchImageLoad/ – Jonathan Marzullo Aug 26 '13 at 23:29
  • 1
    I mean no disrespect but one cannot rely "just" on your word regarding the reliability of your plugin. As mentioned in [`Yevgeniy Afanasyev`'s answer](http://stackoverflow.com/a/26458347/759452), imagesLoaded does a much better job at this & cover the use case you mentioned along with many other corner cases [(see the solved github issues)](https://github.com/desandro/imagesloaded/issues). – Adriano Nov 13 '14 at 17:00
  • @hristo.yankov: please update or remove your links. – Kurt Lagerbier Aug 17 '22 at 20:21
19

For those who want to be notified of download completion of a single image that gets requested after $(window).load fires, you can use the image element's load event.

e.g.:

// create a dialog box with an embedded image
var $dialog = $("<div><img src='" + img_url + "' /></div>");

// get the image element (as a jQuery object)
var $imgElement = $dialog.find("img");

// wait for the image to load 
$imgElement.load(function() {
    alert("The image has loaded; width: " + $imgElement.width() + "px");
});
Dan Passaro
  • 4,211
  • 2
  • 29
  • 33
15

None of the answers so far have given what seems to be the simplest solution.

$('#image_id').load(
  function () {
    //code here
});
Coz
  • 1,875
  • 23
  • 21
  • What's nice about this is that you can get it to trigger for individual images as soon as they load. – Top Cat Feb 14 '18 at 12:34
6

I would recommend using imagesLoaded.js javascript library.

Why not use jQuery's $(window).load()?

As ansered on https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load/26929951

It's a matter of scope. imagesLoaded allows you target a set of images, whereas $(window).load() targets all assets — including all images, objects, .js and .css files, and even iframes. Most likely, imagesLoaded will trigger sooner than $(window).load() because it is targeting a smaller set of assets.

Other good reasons to use imagesloaded

  • officially supported by IE8+
  • license: MIT License
  • dependencies: none
  • weight (minified & gzipped) : 7kb minified (light!)
  • download builder (helps to cut weight) : no need, already tiny
  • on Github : YES
  • community & contributors : pretty big, 4000+ members, although only 13 contributors
  • history & contributions : stable as relatively old (since 2010) but still active project

Resources

Community
  • 1
  • 1
Adriano
  • 19,463
  • 19
  • 103
  • 140
4

With jQuery i come with this...

$(function() {
    var $img = $('img'),
        totalImg = $img.length;

    var waitImgDone = function() {
        totalImg--;
        if (!totalImg) alert("Images loaded!");
    };

    $('img').each(function() {
        $(this)
            .load(waitImgDone)
            .error(waitImgDone);
    });
});

Demo : http://jsfiddle.net/molokoloco/NWjDb/

Dennis Heiden
  • 757
  • 8
  • 16
molokoloco
  • 4,504
  • 2
  • 33
  • 27
  • I found out that this won't work properly if browser returns 304 Not Mofified response for image meaning that the image is cached. – JohnyFree Sep 10 '15 at 20:28
2

This way you can execute an action when all images inside body or any other container (that depends of your selection) are loaded. PURE JQUERY, no pluggins needed.

var counter = 0;
var size = $('img').length;

$("img").load(function() { // many or just one image(w) inside body or any other container
    counter += 1;
    counter === size && $('body').css('background-color', '#fffaaa'); // any action
}).each(function() {
  this.complete && $(this).load();        
});
1

Use imagesLoaded PACKAGED v3.1.8 (6.8 Kb when minimized). It is relatively old (since 2010) but still active project.

You can find it on github: https://github.com/desandro/imagesloaded

Their official site: http://imagesloaded.desandro.com/

Why it is better than using:

$(window).load() 

Because you may want to load images dynamically, like this: jsfiddle

$('#button').click(function(){
    $('#image').attr('src', '...');
});
Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
  • 1
    Actually, imagesloaded does not support the change of src attribute value cross browser. You must create a new image element each time. Try it on Firefox and you will see the issue appearing. – Adriano Nov 19 '14 at 08:01
  • Good point, I've only tested on Google chrome and IE-11 yet. It was working. Thanks. – Yevgeniy Afanasyev Nov 19 '14 at 23:32
  • I did add this cross-browser issue in my question stackoverflow.com/q/26927575 in the point "What you cannot do with imagesloaded", see the imagesLoaded relevant issue on Github https://github.com/desandro/imagesloaded/issues/121 – Adriano Nov 20 '14 at 09:59
1

My solution is similar to molokoloco. Written as jQuery function:

$.fn.waitForImages = function (callback) {
    var $img = $('img', this),
        totalImg = $img.length;

    var waitImgLoad = function () {
        totalImg--;
        if (!totalImg) {
            callback();
        }
    };

    $img.each(function () {
        if (this.complete) { 
            waitImgLoad();
        }
    })

    $img.load(waitImgLoad)
        .error(waitImgLoad);
};

example:

<div>
    <img src="img1.png"/>
    <img src="img2.png"/>
</div>
<script>
    $('div').waitForImages(function () {
        console.log('img loaded');
    });
</script>
James Harrington
  • 3,138
  • 30
  • 32
0

I've found this solution by: @Luca Matteis Here: https://www.examplefiles.net/cs/508021

But I edited it a little bit, as shown:

function showImage(el){
    $(el).removeClass('hidden');
    $(el).addClass('show');

    $(el).prev().removeClass('show');
    $(el).prev().addClass('hidden');
}

<img src="temp_image.png" />
<img class="hidden" src="blah.png" onload="showImage(this);"/>