Shortcuts for jQuery's ready() method

Wilkins picture Wilkins · Oct 11, 2010 · Viewed 27.2k times · Source

I have seen some shortcuts for the ready() method and would like to know which actually happens first, because my test results confuse me..

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

$(window).load(function(){
    alert("window ready");
});

(function($){
    alert("self invoke");
})(jQuery);

Here self invoke happens first, then document, then window. Is the self invoke technique considered a ready() method?

Answer

Nick Craver picture Nick Craver · Oct 11, 2010

The third option is not a shortcut for .ready() (or jQuery related really), the self invoke runs immediately (as soon as it appears in the code), this is probably the shortcut you're thinking of though:

$(function(){
  alert("I'm a ready shortcut");
});

Passing a function into $(func) is a shortcut for $(document).ready(func);. The no-conflict version would look like this:

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