1

Does this:

$(document).ready(function(){
     alert("Hello World");
});

And this:

(function($){
    alert("Hello World");
})(jQuery);

do the same thing?

The former is what I commonly use and the second I have seen used in several plugins. Are they the same, if not then what are their differences and which one to use when?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Vrajesh Doshi
  • 744
  • 2
  • 8
  • 27

1 Answers1

2

They are not the same.

The former is a document.ready event handler. It will run as soon as the DOMContentLoaded event fires. It can also be written like this:

$(function() {
  alert("Hello World");
});

The latter is an Immediately Invoked Function Expression (IIFE). This will be executed immediately (as the name implies). Therefore you need to manually ensure that the DOM is in a state ready to be interacted with before you execute this logic. You can generally do this by placing the script at the end of the body tag, or within it's own document.ready handler. The latter is a little redundant when working with jQuery, though.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339