views:

116

answers:

4

I saw there is an answered question about whether there is a difference between using $(document).ready(function(){}) and $(function(){}) (there isn't), but my question is which is the preferred syntax and why.

I've been using jQuery for about a year and have always used the $(document).ready() syntax; but lately on SO and in some other places, I've seen the $(function()) syntax used more and more.

Is there a preferred syntax that you use and why do you use it? Do you use the shorter syntax solely to save a few characters?

Just a little more background, I'm currently starting a new app from the ground up and want to put some generally accepted best practices and standards in place.

Thanks in advance!

+5  A: 

You can use either, $(function() {}) is just a shortcut that does exactly the same thing.

Personally, I prefer $(function() { }) because...well, I type it a lot, and it's much quicker.

I see a lot of questions of why $(document).load() doesn't work and such because they're not using the right event...I also think$(func) takes some ambiguity out, to me. Do whichever you prefer, what's clearer to you and your team is the best choice here.

Nick Craver
@Nick - thanks. I appreciate the perspective.
David Hoerster
+1  A: 

I find that $(function() {}); is just simpler and saves a few characters. Like you said, it doesn't matter. I think the more important things to worry about are your design patterns for your javascript. They can impact performance, readability, and simplicity.

Bob Fincheimer
I've seen "worrying about your design patterns" screw up a quite lot of code...
Daren Thomas
+3  A: 

I use $(document).ready(function(){}); despite the additional typing. I just prefer having that in my code to remind me exactly when the code is going to run, and for the ability to search for 'ready' to find those sections. It's the same functionality, and I normally take shortcuts, but in this case I don't.

Fosco
readability is a good reason to do something some way, all other things being equal
hvgotcodes
@Fosco - That's why I've used document.ready for so long, because I know what's going on. Thanks!
David Hoerster
+1  A: 

I believe the authors of jQuery recommend using $(document).ready(function(){...}); since it makes your code more transparent.

Squirkle
@Squirkle: When you say 'more transparent', do you mean that it's clearer what you're acting upon (the document element in this case)? Thanks!!
David Hoerster
Exactly. One of the great things about jQuery's syntax is its clarity. By using `$(document).ready(function(){...}` this clarity is maintained from the beginning. I understand that using `$(function() {})` requires fewer keystrokes, but with all of the customizable shortcuts provided by programs like Coda, Espresso, and TextMate, I don't see that these starting keystrokes should ever have to be typed out at all.
Squirkle