The first is a pattern called a closure. It’s not unique to jQuery. You could just as easily write
(function(someVar) {
// Inside the closure, someVar == "test"
})("test");
Basically, you’re manually passing jQuery into the closure by referencing the jQuery
object externally and aliasing it to $
inside the context of the closure.
The second pattern is unique to jQuery. It’s one of the library’s shortcuts to the DOM ready event. The following calls are all equivalent:
jQuery(document).ready(function($) {
// Use $ inside here like normal
});
jQuery.ready(function($) {
// Use $ inside here like normal
});
jQuery(function($) {
// Use $ inside here like normal
});
In all three examples, you’re also passing the jQuery
object into your function as the variable $
so that it’s available within the local scope.