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!
Now playing:
Moby - Extreme Ways
(from 18)
3 Responses
#1 Jason Bunting said...
02-Aug-11 10:23 AMWell, an even better practice, that's been around for a long time now, is to do the following:
#2 julian m bucknall said...
02-Aug-11 12:42 PMJason: 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
#3 Darron Driver said...
02-Aug-11 11:39 PMA pattern I've found quite handy is:
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.
_emphasis_
**strong**
[text](url)
`IEnumerable`
* an item
1. an item
> Now is the time...
Preview of response