What is the difference between?:
$(function(){
});
Y
$(document).ready(function() {
});
I know they wait for the components to load, but would like to know why they are written differently?
Similar English SO question: https://stackoverflow.com/questions/2662778/what-is-the-difference-between-these-jquery-ready-functions
Officially there is no difference :
You can see it in the sources :
However, technically there is a difference that could be useful depending on the circumstances:$(function()
it will not run if jQuery has not been loaded correctly, whereas$(document).ready
it willUpdate: As mentioned in the comments
$(document).ready
it will also not run if jQuery is not loaded. To achieve a similar ( but not identical ) effect without jQuery you can usewindow.onload
.This answer is a translation of the original in English: https://stackoverflow.com/a/2662783/4574 (the last sentence was not in the original)
Seeing that the question dates from the year 2015. Today there is a big difference:
it has been deprecated in jQuery3 and will most likely be deprecated in jQuery4.
Therefore, to keep your code up to date, it is recommended to start using it now:
in all of our code.
This change is clearly explained in the jQuery API:
In conclusion: the recommended way from jQuery3 is:
You can also consult the following questions:
window.onload
and$(document).ready()
?document.ready
deprecated are there changes also forwindow.load
?According to the documentation:
While:
If it is executed after the DOM is loaded, your (usually anonymous) function will be executed immediately.
Conclusion:
Both methods are synonymous. The use of one or the other is a matter of what you prefer. For example, I really like the first one because, as they mention, it is short-lived.
Recommendation:
It is recommended that you use the alias
jQuery
to always obtain the desired behavior in your plugins or components (it does not matter what method you use), examples:Method 1:
Method 2:
Sources
This is also equivalent:
Personally, I recommend using the method by default
on
, and in the case of the methodready
, I recommend not using it, and instead maintain the order of execution of the scripts/functions when you know that the resources (elements/variables, app.js) already exist in the current context, and/or execute those same scripts/functions in callbacks.