using $(document).ready
, it doesn't matter where in the page it is, as it will only execute when the DOM has finished loading. The only code that should go inside $(document).ready
is code that needs to be set up when the DOM has loaded, e.g. event handlers, any effects/animations that you want to run as soon as the DOM has finished loading, etc. Other functions do not need to be in $(document).ready
, such as a function used in sorting an array, named functions called when events are raised, etc.
As has been pointed out, you can have more than one $(document).ready
function on a page, as what you are doing is specifying a function (named or anonymous) to execute when the ready
event (a jQuery event) is raised.
EDIT:
That article that you have linked to in the comments on this answer provides and example of what you are trying to achieve. As an example, you would have a JavaScript file with the following setup to declare a global variable
var myPageLibrary = {
homePage : {
init : function() {
$(document).ready(function() {
/* page specific functions that need to run,
for exmaple, binding event handlers, etc */
});
}
},
aboutPage : {
init : function() {
$(document).ready(function() {
/* page specific functions that need to run,
for exmaple, binding event handlers, etc */
});
}
}
}
/* you might have functions here that are bound to events.
Here is an example */
function showSubMenu(e) {
$(e.target).next('div').show();
}
function hideSubMenu(e) {
$(e.target).next('div').hide();
}
Then in your pages, you would have the following structure (this example uses the home page)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>This is my Home Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="path-to-myPageLibrary.js"></script>
<script type="text/javascript">
myPageLibrary.homePage.init();
</script>
</head>
<body>
<!-- Page content -->
</body>
</html>
with jQuery script file referenced first, followed by myPageLibrary script file, followed by the script block calling myPageLibrary.homePage.init();