Official way to ask jQuery wait for all images to load before executing something

Jquery

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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.
});

Solution 2 - Jquery

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.

Solution 3 - Jquery

$(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:

Demo

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).
 *  @author:  H. Yankov (hristo.yankov at gmail dot com)
 *  @version: 1.0.0 (Feb/22/2010)
 *	http://yankov.us
 */

(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);

Solution 4 - Jquery

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");
});

Solution 5 - Jquery

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

$('#image_id').load(
  function () {
    //code here
});

Solution 6 - Jquery

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

Solution 7 - Jquery

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/

Solution 8 - Jquery

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();        
});

Solution 9 - Jquery

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', '...');
});

Solution 10 - Jquery

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>

Solution 11 - Jquery

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);"/>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimon_WeaverView Question on Stackoverflow
Solution 1 - JquerypaxdiabloView Answer on Stackoverflow
Solution 2 - JqueryalexView Answer on Stackoverflow
Solution 3 - JqueryhyankovView Answer on Stackoverflow
Solution 4 - JqueryDan PassaroView Answer on Stackoverflow
Solution 5 - JqueryCozView Answer on Stackoverflow
Solution 6 - JqueryAdrien BeView Answer on Stackoverflow
Solution 7 - JquerymolokolocoView Answer on Stackoverflow
Solution 8 - JqueryMario MedranoView Answer on Stackoverflow
Solution 9 - JqueryYevgeniy AfanasyevView Answer on Stackoverflow
Solution 10 - JqueryMariusz CharczukView Answer on Stackoverflow
Solution 11 - JqueryCarlos RománView Answer on Stackoverflow