Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does document.ready actually fire?

Tags:

jquery

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?

like image 832
Rohan Avatar asked Nov 15 '11 08:11

Rohan


People also ask

How does document ready work?

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.

What does it mean to be document ready?

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.

Which of the following event fires first document 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.

Where does document ready go?

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.


2 Answers

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

like image 186
Arthur Halma Avatar answered Sep 28 '22 03:09

Arthur Halma


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/

like image 41
Piskvor left the building Avatar answered Sep 28 '22 03:09

Piskvor left the building