I’m a little confused about all the different ways to create a new jQuery object.
the relevent docs seem to be:
http://api.jquery.com/ready/
http://api.jquery.com/jQuery/
From those two docs the following are all equivalent, (with the exception of aliasing or not aliasing ‘$’):
- $(document).ready(handler)
- $().ready(handler)
- $(handler)
- jQuery(function($) {});
- jQuery(document).ready(function($) {});
Is that correct? Did I miss any?
Well, there is another. From the docs:
The other initialiser methods will always run… so you might find yourself declaring
$(document).ready(function() { //stuff }in a number of files for example, and the handler is always run.I’d go with
jQuery(document).ready(function($) {})or$(document).ready(function() {})more often than not… I find that they’re more readable.Another approach would be to call a script just before the closing body tag and in it do something like,
if you need to avoid conflicts with other libraries using $. This is a self-executing anonymous function and it lets you use the alias in its scope without fear of conflicts from other libraries.