I used different jQuery plugins and in some cases they were not working properly (or not working at all) until I embedded them into $(function({ ... }))
.
As example the plugin:
$('#DateTextBox').datetimepicker();
does not work, even if in the plugin web site it is used exactly in the same form. Placing it inside $(function()) it turns working perfectly:
$(function ()
{
$('#DateTextBox').datepicker();
});
What the statement "$(function ())" brin开发者_JAVA技巧gs exactly? I tried to search in the same jQuery web site but I did not find an answer.
What the statement "$(function ())" brings exactly?
It makes sure your code will not get executed before the page has finished loading. It is a shorthand for
$(document).ready(function () {
// ...
});
Read: http://api.jquery.com/ready/
$(function ()
means
$(document).ready(function() {
It wait for dom to be loaded.
Its not that you're using the plugins wrongly. You're probably invoking them before your document is ready, or before your scripts are loaded, or some such problem with the order of your code.
$(function() {
});
is equivalent to
$(document).ready(function() {
});
While document.ready
is the right solution for most of your situations, also ensure that:
- you load jquery before all other plugins
- your page is ready before your scripts start executing.
If possible, follow this recommendation from YSlow - Load all your scripts at the end of your page.
If I remember correctly, $(function () {})
is the same as $.ready(function () {})
, so the code will only get executed when the page is ready.
Look at the documentation for the ready
function because it does not behave exactly like the standard load
event.
精彩评论