I have seen this (I’m also using it):
$(document).ready(function(){
// do jQuery
})
and also this (I have tried lately):
(function(){
// do jQuery
})(jQuery)
both work fine.
What is the difference of the two (except on how it looks)?
Which one is more proper to use?
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
jQueryobject as an argument to avoid conflict ), thereby immediately invoking the functionThe right function to use depends on when you want the function to run.
If you want to run a function on
DOMReady( thereadyevent ), you can use$( document ).readylike you mentioned or the shorthand$( function() {...} ).Otherwise, if you want to run a function immediately and have anonymous function scope, use the second example.