Should everything be within document.ready(function() {});?
Yes and no. In large scale JavaScript applications, I initialize my main controllers into the global scope from this event handler. However, there is code that doesn't need to wait for the DOM to be ready, specifically: code that doesn't rely on the DOM. I think that's pretty straight forward. For example, I declare configuration objects classes, functions, etc outside of this event handler.
Is there any reason to have anything outside of document.ready(function() {});?
Sure, for the reason's touched on above. Mainly, code that doesn't require DOM interaction shouldn't wait for the DOM to load, especially if it can execute asynchronously to the DOM loading (e.g.: function definitions, configuration objects, etc).
Also, not including all of your code in one event handler keeps things more organized, allows you to modularize code, use proper design patterns, etc.
Is the code within document.ready(function() {}); inaccessible by outer code?
Again, yes and no. If you declare it as local with var
then it is yes, it is inaccessible by the outer scope as it is local to the event handler; otherwise, it is in the global scope and is accessible to the outer scope. Here's an example (hosted here: http://jsbin.com/uriqe)
JavaScript
var foo = function() {
alert(global);
return false;
}
$(document).ready(function() {
global = "you can see me!?";
alert("global is initiated");
});
HTML
<body>
<p><a href="#" onclick="foo()">click me</a></p>
</body>
onclick
rather than unobtrusive method event attachment in $(document).ready()
is used intentionally to avoid any questions/arguments about foo
having access to global
via the closure property.
Edit: I thought I made it clear in the previous sentence, but onclick
is used intentionally to avoid confusion between global scope and the closure property, but I'm not advocating the use of onlick
. Of course it's a bad practice and you shouldn't be using it.