I was wondering what was the best way to call a function when the DOM was ready. I mean, I know that
$(document).ready(function(){})
and
$(function(){})
were the same way to implement the action ready of the DOM. My question is more about performance, I usually wrote my JS like this :
$(document).ready(function(){
console.log('Hello World');
});
But a teacher once tryed to make me change my mind and write like this :
function main(){
console.log('Hello World!');
}
$(document).ready(main);
The truth is I never did that but now I am wondering what is the best way in terms of performance... If I put everything in an external function does it load faster?
In fact I was writting as the first way because I don't want my functions to be accessible from the DOM so I was doing this :
$(document).ready(function(){
function Hello(){
console.log('Hello World');
}
Hello();
});
In this way it's impossible to use the function Hello from the DOM or from the console... And so I didn't like my teacher's way. But now I use to encapsulate all my code in an anonymous function and in this way I'm more cumfortable to write like this :
(function($){
function Hello(){
console.log('Hello World!');
}
$(document).ready(Hello);
})(jQuery);
And that's why I was wondering about performance between the two methods, what do you guys think?
- that way the DOM will already be loaded, and your script won't slow down loading before it's even needed.
– powerbuoy Jan 29 '18 at 15:58