3

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 ())" brings exactly? I tried to search in the same jQuery web site but I did not find an answer.

4 Answers 4

5

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Now it is much more clear why the plugin was not working! Thanks a lot.
4
$(function ()

means

$(document).ready(function() {

It wait for dom to be loaded.

Comments

4

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:

  1. you load jquery before all other plugins
  2. 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.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.