Is there any difference between using:
$(document).ready(function(){
vs.
$(function(){
Does one of these work better than the other in some way, or is the first just a shorthand version of the first?
jQuery ready() Method The ready event occurs when the DOM (document object model) has been loaded. Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above. The ready() method specifies what happens when a ready event occurs.
The jQuery document ready ( $(document). ready() ) method was implemented to execute code when the DOM is fully loaded. Since it executes the given function when all DOM elements are available, you can be sure that trying to access or manipulate elements will work.
$( document ).ready() Code included inside $( window ).on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready. // A $( document ).ready() block. console.log( "ready!" );
ready() method will only run after the DOM has loaded. So you'll only see "Hello World!" in the console after the $(document). ready() method has started running. In summary, you can write all your jQuery code inside the $(document).
The latter is the short version of ready handler.
The:
$(function(){
})
is short version of this:
$(document).ready(function(){
}
Both do the same and one task.
jQuery is doing to a good deal with its slogan:
'Code less, do more'
From the docs:
All three of the following syntaxes are equivalent:
* $(document).ready(handler) * $().ready(handler) (this is not recommended) * $(handler)
There is also $(document).bind("ready", handler). This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed.
The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.
HTH
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