jQuery document ready function

tmbrggmn picture tmbrggmn · Apr 22, 2011 · Viewed 37.4k times · Source

Are the end results of the following jQuery snippets identical?

Snippet 1:

$(function() { alert('test!'); });

Snippet 2:

$(document).ready(function() { alert('test!'); });

In other words, is $(function(){}) just shorthand for $(document).ready(function() { });?

The reason I'm asking is because we're seeing some strange issues with a small application we've built using jQuery and jQuery UI. Occasionally, when performing a form submit action by clicking a button the browser window will just freeze. We can still use the underlying browser window (the one that launches the pop-up) until we perform some actions there. The users can only continue by force closing the browser (Internet Explorer, obviously). We suspect this is related to the Acrobat PDF plug-in, but I'm just checking all the angles here, because I found this issue which seems to exhibit similar behaviour.

Answer

Andrei Andrushkevich picture Andrei Andrushkevich · Apr 22, 2011

All three of the following syntaxes are equivalent:

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

Aliasing the jQuery Namespace

When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code:

jQuery(document).ready(function($) {
  // Code using $ as usual goes here.
});