-2

What is an example of a time where you would want to use jquery.ready()? When would you want the code to run before the DOM is fully constructed?

EDIT: Sorry! That's not what I meant! I meant the opposite! ready() indeed makes the code run after the DOM is constructed and quite often this is what you want. But I just learned about the function delegate() which I used to make a function be called on things that were later added into the DOM via ajax. For this I did not use ready(), just delegate() and I was trying to figure out why... I am very sorry for the confusion.

user1015214
  • 2,733
  • 10
  • 36
  • 66
  • @Sparky672 To be more precise, it runs the enclosed code after the DOM is fully loaded. I know I'm nitpicking on grammar, but someone in the future may read this and think that the line prevents all code from running until after the DOM is fully loaded. – Whetstone Nov 08 '11 at 18:38
  • @Whetstone, "comments" typically make some assumptions since they're not supposed to be an "answer" to the OP. Otherwise, we're here all day turning simple comments into full blown answers. Nitpicking indeed. – Sparky Nov 08 '11 at 18:45

3 Answers3

2

I recommend reading the documentation for the ready event: http://api.jquery.com/ready/

The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

Jasper
  • 75,717
  • 14
  • 151
  • 146
1

The complete opposite actually. $.ready() runs after the DOM is loaded, any normal script runs before.

Whetstone
  • 1,199
  • 8
  • 8
0

You use $.ready() whenever you need to interact with DOM elements for example manipulating/animating/adding/deleting/replacing them.

Note however that you can not use $.ready() to work with images or frames unless they have fully loaded which is usually done by using onload event instead.

When would you want the code to run before the DOM is fully constructed?

Actually you use $.ready() AFTER the DOM has fully loaded.

You can read thorough documentation here:

Sarfraz
  • 377,238
  • 77
  • 533
  • 578