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?
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
The document ready event signals that the DOM of the page is now ready, so you can manipulate it without worrying that parts of the DOM has not yet been created. The document ready event fires before all images etc. are loaded, but after the whole DOM itself is ready.
ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.
The document ready function will wait until the DOM is loaded before running. So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded.
$(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)
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With