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
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements.
$( document ).ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
jQuery Document Ready Example $(document). ready(function() { //DOM manipulation code }); You call jQuery's $ function, passing to it the document object. The $ function returns an enhanced version of the document object.
$( init ); The init() function itself uses jQuery to fade all h1 headings in the Web page out, then in. Take a look at the first line of the function: $('h1').
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 (var
s within the anonymous function) that are not actually globals.
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() {
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With