keybored
keybored

Reputation: 5248

Necessity of .ready() in jQuery

I've seen various examples use this and I'm curious to know, is it dangerous not to wrap jQuery code in the following?

$(document).ready(function () {});

I know what it does and I know why you do it but I'm curious if it is more unsafe or just bad practice/style to not have it? Thanks!

Upvotes: 3

Views: 156

Answers (5)

Peter Bailey
Peter Bailey

Reputation: 105878

I think you should also be aware of jQuery's $(window).load() and how it differs from $(document).ready()

Read more about it here

Upvotes: 0

david
david

Reputation: 18258

You use it if your code needs to access the DOM.

If you're just setting up classes and modules, but not actually running them, then you don't need to wrap them in the ready handler.

However, if you're doing something that requires elements to be loaded (like, adding event handlers) then you need to do it in the ready() event.

EDIT:

Here is an example: http://jsfiddle.net/ctrlfrk/43n8U/ Try commenting out the addHandler functions and see what happens.

(Note that I've set jsfiddle to run this code in the head tag, by default it usually places the code in the onload event, which negates the need for the ready handler)

Upvotes: 6

Cray
Cray

Reputation: 2454

Wrapping your code in ready() function only delays the running of that code until the page has been loaded. The code does not get "safer" somehow.

But many times you want to run some code that will query the DOM that is created after the script-tag that your code is in, or simply need some structures from the document that are placed after that script tag. If that is the case, then ready() is for you.

But generally there is no valid reason not to use ready() function, so that's why everybode almost always use it.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

It depends on where you are placing your scripts. If you add a script tag just before the closing <body> you don't need to use it because the DOM will already be loaded. On the other hand if you place your script tag inside the <head> section and access the DOM you absolutely need to use it or your script won't work because at the moment your script executes the browser hasn't yet read and parsed the DOM.

Upvotes: 4

Jason Benson
Jason Benson

Reputation: 3399

See this (already answered)

jQuery ready function aliases

for those that the above is tl;dr; :

Additional reading: http://api.jquery.com/ready/

Upvotes: 1

Related Questions