I’ve already encapsulated my javascript in
jQuery(document).ready(function($) {
});
I was wondering what the implications were of calling functions inside of it via these two ways:
jQuery(document).ready(function($) {
$(function () {
// do something
});
});
vs
jQuery(document).ready(function($) {
(function () {
// do something
})();
});
edit:
I also wanted to know which of the two would be the more “correct” manner of doing things? Feel free to add your own implementation.
In difference lies in the order of execution:
Code inside the inner
readyhandler is executed after the code in the outer handler: http://jsfiddle.net/nmD8b/.Code inside the immediate function expression is executed right where the function is defined, i.e. before code following the expression: http://jsfiddle.net/nmD8b/.
If you want to scope variables, use the second way. The first way does not make a lot of sense, you should only register
readyevent handlers when you actually need them. In this case, the DOM is already ready, because you bind the handler inside another ready handler.If you don’t want to scope variables, use neither of them. Just put all your code inside the outer handler.