Search code examples
javascriptjqueryperformancedomready

best way to call $(document).ready() function


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?


Solution

  • TL;DR;

    Do whatever you like! There is no such impact to your site.

    What COULD be the best way?

    In general, you can do whatever you like, but there are some facts that lead us in the right direction, which tells us, that jQuery(function($) {}); is a pretty good choice!

    Why? Let's see ...

    Fact 1: It's the most shortest way. Okay, an IIFE might be shorter, but this is not a real ready state, just an immediately function call.

    Fact 2: It is the preferred way to write a ready state by jQuery itself. Since v3 it's mentioned to use this way.

    Fact 3: Why would you use an IIFE to pass in the jQuery object? It's not needed, because the first function parameter is the jQuery object.

    Fact 4: It is good to use and to work with and without jQuery noConflict mode. Because the first parameter is the jQuery object, you can always work with $ inside of the ready state, and only have to write jQuery once.

    Fact 5: You don't use a named function, just an anonymous closure. In nearly 99,99% of all cases, you only use the ready state handler once. So there is no need for a named function or a function stored inside a variable.

    So in my opinion, this is the best choice in general:

    jQuery(function($) {
        // ...
    });