Let\'s consider the following case:
There is a 2.5MB image in an
tag and I\'m on a slow connection which takes considerable time to download
Everything inside $(document).ready()
will load as soon as the DOM is loaded and before the page contents (html) are loaded.
As in the Documentation:
While JavaScript provides the
load
event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed.
So it's when the <img>
tags are loaded, but not the actual data of the images.
An example of loading the images and triggering an event when they are loaded:
<img data-src="images.jpg" />
<img data-src="images.jpg" />
$(document).ready(function() {
$("img").load(function() {
alert('image loaded');
}).each(function() {
$(this).attr("src", $(this).attr("data-src"));
});
});
To quote the documentation for ready():
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. [...] The handler passed to .ready() is guaranteed to be executed after the DOM is ready [...]
So yes, it may fire before images are loaded (that's what it's for, after all). It even adresses this explicitly:
In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
The documentation for load()
is here: http://api.jquery.com/load-event/
$(document).ready(...)
Fire when the DOM is loaded (even if multimedia no loaded yet)
$(window).load(...)
Fire when all the content is loaded (when the progress indicator which shows the loading process is gone)