How should I initialize jQuery?

The first example runs the function when the DOM tree is built. The second example runs the function right away.

If you look closely, in the second example, there are two parentheses after the function declaration ( in this particular case, you pass in the global jQuery object as an argument to avoid conflict ), thereby immediately invoking the function

The right function to use depends on when you want the function to run. If you want to run a function on DOMReady ( the ready event ), you can use $( document ).ready like you mentioned or the shorthand $( function() {...} ).

Otherwise, if you want to run a function immediately and have anonymous function scope, use the second example.

Leave a Comment