36

Possible Duplicate:
What is the difference between these jQuery ready functions?
jquery: Choosing a document.ready method

What is the difference between doing this

$(function() {
    $("a").click(function(event){
        alert("Thanks for visiting!");
    });
});

and this

$(document).ready(function(){
    $("a").click(function(event){
        alert("Thanks for visiting!");
    });
});
James Hill
  • 60,353
  • 20
  • 145
  • 161
Matt Morey
  • 984
  • 1
  • 11
  • 14
  • The former is less wordy and, when you get used to the idiom, more readable. Otherwise they have the same effect. – tvanfosson Feb 22 '12 at 14:11

3 Answers3

48

They are the same. Check out the jQuery .ready() docs. Here's a quote from the docs:

All three of the following syntaxes are equivalent:

$(document).ready(handler)

$().ready(handler) (this is not recommended)

$(handler)

James Hill
  • 60,353
  • 20
  • 145
  • 161
12

There is no difference in functionality between your examples - they both bind to DOM ready.

For reference, there are two points at which you can bind your jQuery code.

The first will execute when the DOM is ready (both are equivalent):

// full example
$(document).ready(function() {
  // code...
});

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

// ES6 example with $ aliased, note this is not supported in IE
jQuery($ => {
  // code...
});

The second will execute when the page has finished loading all images, stylesheets etc.

$(window).on("load", function() {
  // code...
});

The second is useful when you need to get the width() or height() of an image. These properties are only available once the image has completely downloaded to the client system.

Also note that $(window).load(fn); is now deprecated and should no longer be used.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Of course, in addition to binding, it's important to remember that initialization code sometimes needn't be bound to any event. Some can run as soon as it's read, per this [article](http://encosia.com/dont-let-jquerys-document-ready-slow-you-down/) by [Dave Ward](http://encosia.com/about-dave-ward/). – MarkDBlackwell Apr 30 '13 at 14:39
7

All three of the following syntaxes are equivalent:

$(document).ready(handler) 
$().ready(handler) (this is not recommended) 
$(handler) 

http://api.jquery.com/ready/

Sanjay Goswami
  • 1,386
  • 6
  • 13