JavaScript: handy hint for jQuery document ready handlers

Like 99% of all jQuery users, I write the code I want executed when the document is ready like this:

$(function () {
  // code using $ for the jQuery function
});

Except… What happens if someone calls $.noConflict() and $ is no longer valid? Do I have to resort to using jQuery() all over the place, just to be sure?

Answer: no. It seems – and I only discovered this moments ago – the document ready handler gets passed the jQuery function as the first and only argument. You can write this instead:

jQuery(function ($) {
  // code using $ for the jQuery function
});

Or, if you are really paranoid:

jQuery(function ($, undefined) {
  // code using $ as the jQuery function
  // and undefined means what it says
});

Magic!

Album cover for 18Now playing:
Moby - Extreme Ways
(from 18)


Loading similar posts...   Loading links to posts on similar topics...

3 Responses

 avatar
#1 Jason Bunting said...
02-Aug-11 10:23 AM

Well, an even better practice, that's been around for a long time now, is to do the following:

(function($) {

  /* any and all code for which you want to use the $ alias */

})(jQuery);
julian m bucknall avatar
#2 julian m bucknall said...
02-Aug-11 12:42 PM

Jason: Well sure (and I talked about this some months back), but it's no longer a document ready function. It's an autoexecuting anonymous function, or an Immediately-Invoked Function Expression (or IIFE).

They are different things, each with their place and utility.

Cheers, Julian

 avatar
#3 Darron Driver said...
02-Aug-11 11:39 PM

A pattern I've found quite handy is:

var Setup = (function($) {
    $(function(){
       // condition to be met
       if ($('#element_on_page')) {
         Setup.init();
       }
    });
    function _init() {
        // code to be executed
    }
    return {
        init:_init 
    };
})(jQuery);

Has the advantage of being self-executing while still waiting for document ready. There is probably a better way of doing this, your thoughts?

Leave a response

Note: some MarkDown is allowed, but HTML is not. Expand to show what's available.

  •  Emphasize with italics: surround word with underscores _emphasis_
  •  Emphasize strongly: surround word with double-asterisks **strong**
  •  Link: surround text with square brackets, url with parentheses [text](url)
  •  Inline code: surround text with backticks `IEnumerable`
  •  Unordered list: start each line with an asterisk, space * an item
  •  Ordered list: start each line with a digit, period, space 1. an item
  •  Insert code block: start each line with four spaces
  •  Insert blockquote: start each line with right-angle-bracket, space > Now is the time...
Preview of response