Mantisimo
Mantisimo

Reputation: 4283

JQUERY $(function() { initialisation

I've been working with JQuery for some time now and I've always used the following to initalise my javascript:

$(document).ready( function() {
// Initalisation logic
});

However, recently I've noticed a lot of examples using the following:

$(function() {

});

Whats the difference?

Thanks

Upvotes: 5

Views: 1095

Answers (3)

finneycanhelp
finneycanhelp

Reputation: 9248

The difference is a matter of style. One is just a shortcut of the other. :) See http://api.jquery.com/jQuery/ near the bottom where it says "Executes the function when the DOM is ready to be used"

When I asked one of the jQuery UI people what they preferred, he said he preferred the more verbose way. However, people in my shop use this version:

$(function() {

});

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1073998

Basically, there isn't one. The $(...) format is a shortcut. See the API docs for jQuery() for details.

I like to use it like this:

jQuery(function($) {
    // ...all of my jQuery-specific code here...
});

...because then if I need to, I can use noConflict if I end up having to mix something into the page that also wants the $ symbol, but I can still use $ in my code (because jQuery passes itself into the callback as the first argument, and as you can see I'm accepting that argument as $ in my callback function — and so that shadows any global $ symbol that another library might be using). The above also has the advantage that I can have symbols global to my code (vars within the anonymous function) that are not actually globals.

Upvotes: 8

orlp
orlp

Reputation: 117641

The difference is that the first is more readable. So please just use this one.

$(document).ready(function() {
// Initalisation logic
});

Upvotes: 1

Related Questions