When do you define javascript functions inside $ (document) .ready (), and when not?
If functions should be available around the world (which may indicate a poor design for your application), you must define them outside the ready
handler.
Is it enough to just put the javascript code inside $ (document) .ready ()?
See above.
What happens when you do not?
Depends on what your JavaScript code does and where it is located. In the worst case, you will get runtime errors because you are trying to access the DOM elements before they exist. This will happen if your code is in head
, and you not only define functions, but also try to access DOM elements.
For example, I use regular jQuery selectors that do something when you click on things. If you do not wrap them with a document. Already what harm?
There is no βharmβ per se. It just does not work if the script is in head
because the DOM elements do not exist yet. This means that jQuery cannot find and bind a handler to them.
But if you place the script immediately before the closing body
tag, then the DOM elements will exist.
To be safe, whenever you want to access DOM elements, put these calls in the ready
event handler or in functions that are called only after loading the DOM.
As a jQuery tutorial (you should read it) it already says:
As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events, etc., as soon as the DOM is ready.
To do this, we register the finished event for the document.
$(document).ready(function() {
To give a more complete example:
<html> <head> <script> function foo() { </script> </head> <body> <div id="question">The answer to life, the universe and everything</div> <div id="answer"></div> <button>Show the answer</button> <script> </script> </body> </html>