jQuery anonymous and callback function declarations

JavaScript enables you to create anonymous functions to be executed immediately or when the document is ready, and also allows you to freely pass functions around to be executed at a later time. The default short-hand notation for jQuery wrapper is $, and unless your webpage has a conflict with other javascript libraries you may freely use $ to wrap any jQuery scripts. Since there are many variations of anonymous function calls, they are worth mentioning here.

1. The most common place to write the jQuery code is inside the document ready enclosure which ensures the code is executed when document is ready to be manipulated. This is more efficient than window.onload function, which waits until all document including images are finished loading (see below).

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

window.onload = function() {
}

2. This is a short-hand notation for "document ready" anonymous function declaration. This will execute when the document is ready to be manipulated.

$(function(){
});

3. This is anonymous function wrapped in a self-contained closure. It gets executed immediately.

(function(){
})();

4. This is identical to #3 above, except that it defines $ as a short-hand notation for jQuery inside the closure. You may want to do this if $ is bound to another library control, and you want to use $ to wrap jQuery inside the closure.

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

Comments

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.