Manoj Kalla
What is difference between $(document).ready(function(){ vs $(function(){ ?

What is difference between

$(document).ready(function(){

});

vs

$(function(){

});

By Manoj Kalla in .NET on Aug 16 2019
  • Sonu Gupta
    Aug, 2019 23

    $(document).ready() { }
    This uses the j-query library to detect when the DOM is ready for JavaScript to execute. Specifically, you are passing in the document object as an argument to the j-query constructor and calling the ready() function on it, which will wait until the ready event fires.

    (function() { }) ()
    This is an anonymous function that instantaneously runs.
    The difference is that if you were to put these two lines next to each, whether both will run will depend on where the page state is. Once your code reaches the anonymous function it will run it regardless. Once it hits the j-query snippet, if your page is still loading dependencies, etc. and the ready event isn’t fired then your code in the curly braces will not run until it is.

    • 2
  • Priyanka Jain
    Aug, 2019 23

    $(document).ready() is JQuery's ready event handler the function you pass to the ready method is added to the queue of functions that are to be invoked once the document is loaded$(function) is an immediately invoked function Expressions. This function will be invoked as soon as the browser has parsed it, which may or may not be before the document has finished loading

    • 2
  • Vincent Maverick Durano
    Aug, 2019 29

    1. $(function() {
    2. //some code
    3. });

    Is a Shorthand version of:

    1. $( document ).ready(function() {
    2. //some code
    3. });

    So technically they are both the same.

    • 1
  • Bidyasagar Mishra
    Sep, 2019 3

    $(function(){
    });
    is the shortest version of $(document).ready(function(){})

    • 0
  • Ankit Kanojia
    Aug, 2019 28

    Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document).ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS