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 the document is ready to be manipulated. This is more efficient than window.onload function, which waits until all documents 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 an 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);

Share this post

Comments (0)

    No comment

Leave a comment

All comments are moderated. Spammy and bot submitted comments are deleted. Please submit the comments that are helpful to others, and we'll approve your comments. A comment that includes outbound link will only be approved if the content is relevant to the topic, and has some value to our readers.


Login To Post Comment