tags:

views:

56

answers:

3

While John Resig's recommendation is, quite rightly, to declare all events within a jquery.document.ready() function, I know that you don't actually have to put everything in there. In fact, there are cases where it may be more appropriate to deliberately put methods outside of the ready event.

But what are those cases? Obviously best practice dictates that all events are declared within the ready event, so what would best practice be for declarations outside that event?

Edit Remember, I'm not just after the less-obvious stuff, but I'd like to get a good account of the obvious parts as well. For example, if I'm writing a plugin, I wouldn't encapsulate that code in a jquery.document.ready() call.

A: 

I can think of anything you like to do which does not require a DOM element to be successfully loaded already.

jAndy
+4  A: 

Putting things into the ready event makes sure that the full DOM is available at the time the function is called.

Any functions and events not depending on the DOM don't need to be put into the ready event.

Sometimes you even need to keep things out of the ready function, e.g. document.write() commands that are supposed to place HTML into the markup at the position the script is at.

Pekka
DON'T use document.write() ! :p
jAndy
@jAndy good point, but if you *want* to use it, you need to do so outside the event. :)
Pekka
+1  A: 

Put everything in jquery.document.ready() which:

  • changes layout (you want to prevent page-flicker)
  • is needed for user-interaction, to make the page usable

What can postponed is:

  • everything not important for the user, for example analytics, ads
  • things (slightly) improving the user experience
  • fetching non-essential widgets or buttons to be added to the page
edwin
@Pekka's answer is quite right and, while it has been well-voted, I personally think this answer better satisfies what I'm actually asking.
Phil.Wheeler