Reputation: 540
What is the difference between using
$(function(){
});
and
$(document).ready(function(){
});
Have tried both , both work well but what happens at runtime.
Upvotes: 1
Views: 77
Reputation: 705
1.==>> $(document).ready(function(){ }); -This is to prevent any jQuery code from running before the document is finished loading. -This also allows you to have your JavaScript code before the body of your document, in the head section.
2.==> $(function(){
}); -This is shorter method for the document ready event.
Both methods are works but the document ready event is easier to understand when reading the code.
Upvotes: 0
Reputation: 1075587
The both do exactly the same thing, but the second form is not recommended in jQuery v3. See here and here in the documentation. From that second link:
jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:
$( handler ) $( document ).ready( handler ) $( "document" ).ready( handler ) $( "img" ).ready( handler ) $().ready( handler )
As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated.
Upvotes: 1