1

When I was first learning JavaScript, I sort of picked up the habit of wrapping any scripts I wanted to execute the moment the page loaded inside a construct like this:

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

Having learned more since then, I'm under the impression I could just as easily toss the jQuery and write:

(function(){
    //code
})();

Are these two methods equivalent in end result? Is one preferable? Am I entirely mistaken about one or both? What is the standard best practice for "execute on document ready"?

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
  • No they are doing different things. The second one doesn't wait for the DOM to be ready. – PeeHaa Dec 26 '13 at 02:31
  • possible duplicate of [start javascript code with $(function, etc](http://stackoverflow.com/questions/12008843/start-javascript-code-with-function-etc) – Joseph Silber Dec 26 '13 at 02:38

2 Answers2

6

They're not the same thing at all. The first is a document.ready event, that typically looks like this:

$(document).ready(fn);

But jQuery lets you use a shortcut:

$(fn);

The second code is an IIFE (Immediately Invoked Function Expression), all it does is create a closure, so you don't expose variables to the global scope, then executes itself right away.

When you use jQuery, putting all your code in a ready event is good practice, an incidentally you create a closure too, so everything in there is "private" too. But you don't need the ready event, if you add the code before your closing body tag. You can use as many IIFEs as you want, but you typically only use one ready event, since the event only runs once.

In conclusion, document.ready triggers when the event occurs. IIFEs let you encapsulate code.

elclanrs
  • 92,861
  • 21
  • 134
  • 171
1

The first one waits for document ready, so use it if you put your code in the head of the document.

Use the second method (IIFE) if you put all of your JavaScript at the bottom of the page (which you should anyhow be doing).


There's also a good practice of passing jQuery into that function:

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

...so that in case another library has overwritten the global $ variable, you can still safely use it within the IIFE.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292