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.
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'sload
event.e.g.:
With jQuery i come with this...
Demo : http://jsfiddle.net/molokoloco/NWjDb/
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:
Because you may want to load images dynamically, like this: jsfiddle
$(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
My solution is similar to molokoloco. Written as jQuery function:
example:
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
jollyroger
JPEG files (or other suitable ones):With that, the alert box appears before the images are loaded, because the DOM is ready at that point. If you then change:
into:
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: