Reputation: 1805
Let's consider the following case:
There is a 2.5MB image in an <img>
tag and I'm on a slow connection which takes considerable time to download that image. If I'm putting the document.ready()
in the head tag, then will it wait for the image to be downloaded or it will fire when all the HTML is downloaded?
In case it fires when all the HTML is downloaded, how do I avoid it?
How do I make the .ready()
function fire after the 2.5MB data transfer?
Upvotes: 12
Views: 13562
Reputation: 10305
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"));
});
});
Upvotes: 2
Reputation: 4001
$(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)
Upvotes: 17
Reputation: 32468
Everything inside $(document).ready()
will load as soon as the DOM is loaded and before the page contents (html) are loaded.
Upvotes: 1
Reputation: 92752
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/
Upvotes: 3