1

I already know about the advantages of wrapping your Javascript in a function like this:

(function () {
    // code goes here
}())

But I've seen some scripts which accomplish this by passing the wrapper function to the jQuery object:

$(function () {
    // blah blah blah blah blah
});

What's the advantage of doing it this way, or is it just a matter of personal taste? And does doing it the second way negate the need for $(document).ready()?

GMA
  • 5,816
  • 6
  • 51
  • 80
  • 2
    This first one is a function that is executed immediately, the second one is the jQuery syntax to execute something on page load, and yes it is a replacement for $(document).ready() – mplungjan Aug 21 '13 at 08:29
  • 4
    Second is the same as `$(document).ready()`. Read here in the docs http://api.jquery.com/ready/ – elclanrs Aug 21 '13 at 08:29

3 Answers3

0

Your first example is just standard JavaScript a self executing function, the second one is jQuery specific, and is a shortcut for $(document).ready(function () {});

see the jQuery documentation

and also this question for more info on self executing functions

Community
  • 1
  • 1
NDM
  • 6,731
  • 3
  • 39
  • 52
0

The first one

(function () {
    // code goes here
}())

That is self executing function.

And the second function is jquery specific.

If you see the docs

The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.

The .ready() method is typically used with an anonymous function:

$(document).ready(function() {
  // Handler for .ready() called.
});

Which is equivalent to calling:

$(function() {
     // Handler for .ready() called.
    });
Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

(function(){}()) is an IIFE (Immediately-Invoked Function Expression) and is just an function executing Immediately
$(function(){}) is an jQuery callback fro when the browser is ready

i often have to add jQuery to sites that have mootools on them so to avoid $ conflicts i do somthing like this:

;(function($, app, undefined){
    // code here
}(jQuery, myApp = window.myApp || {}))
VeXii
  • 3,079
  • 1
  • 19
  • 25